Motty/Auto-resizing background image using Canvas ( JavaScript)
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Conforming XHTML 1.0 Strict Template</title>
</head>
<body>
<h2>Auto-resizing the background image using Canvas</h2>
<canvas id="myCanvas" style="width: 100%; height: 100%; position: absolute; left: 0px; top: 0px; z-index: -1;"></canvas>
<script type="text/javascript">
var context = document.getElementById('myCanvas').getContext('2d');
var w = document.body.clientWidth;
var h = document.body.clientHeight;
img = new Image();
img.src='http://i201.photobucket.com/albums/aa236/Mottie1/testsite/screenshots/bg1.jpg';
img.onload = function () {
context.drawImage(this,0,0,300,150);
};
</script>
</body>
</html>
The canvas drawImage size default is 300 x 150, so it's using the CSS to resize the canvas. Example posted at http://pastebin.me/76aed7005b1b413ea3c479287f4dbd59
SFLWebDev/Facebook IFrame Tab Resize Fix ( JavaScript)
(function() {
FB.Canvas.setAutoResize();
document.body.addEventListener('onresize', 'FB.Canvas.setAutoResize');
})();
This script will handle any vertical resizing issues with a Facebook IFrame tab application, such as the resizing of the frame when elements expand, such as a Facebook Comments plugin. It uses the "FB.Canvas.setAutoResize" method from the Facebook JavaScript SDK, so that must be initialized with a Facebook Application ID; for more information, see http://developers.facebook.com/docs/reference/javascript/
neoline/Auto-resizable Background ( CSS)
/* Use this markup: */
<div id="background">
<img src="img.jpg" class="stretch" alt="" />
</div>
*/ with the following css: */
#background {
width: 100%;
height: 100%;
position: absolute;
left: 0px;
top: 0px;
z-index: 0;
}
.stretch {
width:100%;
height:100%;
}
ayaz/HTML5 Canvas slideshow ( HTML)
HTML
<div id="slideshow">
<ul class="slides">
<li><img src="/images/gallery/tc3.jpg" alt="Marsa Alam" /></li>
<li><img src="/images/gallery/tc0.jpg" alt="Marsa Alam" /></li>
<li><img src="/images/gallery/tc17.jpg" alt="Marsa Alam" /></li>
<li><img src="/images/gallery/tc2.jpg" alt="Marsa Alam" /></li>
<li><img src="/images/gallery/tc16.jpg" alt="Marsa Alam" /></li>
</ul>
<span class="arrow previous"></span>
<span class="arrow next"></span>
</div>
Java Script
<script type="text/javascript">
$(window).load(function(){
// We are listening to the window.load event, so we can be sure
// that the images in the slideshow are loaded properly.
// Testing wether the current browser supports the canvas element:
var supportCanvas = 'getContext' in document.createElement('canvas');
// The canvas manipulations of the images are CPU intensive,
// this is why we are using setTimeout to make them asynchronous
// and improve the responsiveness of the page.
var slides = $('#slideshow li'),
current = 0,
slideshow = {width:0,height:0};
setTimeout(function(){
if(supportCanvas){
$('#slideshow img').each(function(){
if(!slideshow.width){
// Saving the dimensions of the first image:
slideshow.width = this.width;
slideshow.height = this.height;
}
// Rendering the modified versions of the images:
createCanvasOverlay(this);
});
}
$('#slideshow .arrow').click(function(){
var li = slides.eq(current),
canvas = li.find('canvas'),
nextIndex = 0;
// Depending on whether this is the next or previous
// arrow, calculate the index of the next slide accordingly.
if($(this).hasClass('next')){
nextIndex = current >= slides.length-1 ? 0 : current+1;
}
else {
nextIndex = current <= 0 ? slides.length-1 : current-1;
}
var next = slides.eq(nextIndex);
if(supportCanvas){
// This browser supports canvas, fade it into view:
canvas.fadeIn(function(){
// Show the next slide below the current one:
next.show();
current = nextIndex;
// Fade the current slide out of view:
li.fadeOut(function(){
li.removeClass('slideActive');
canvas.hide();
next.addClass('slideActive');
});
});
}
else {
// This browser does not support canvas.
// Use the plain version of the slideshow.
current=nextIndex;
next.addClass('slideActive').show();
li.removeClass('slideActive').hide();
}
});
},100);
// This function takes an image and renders
// a version of it similar to the Overlay blending
// mode in Photoshop.
function createCanvasOverlay(image){
var canvas = document.createElement('canvas'),
canvasContext = canvas.getContext("2d");
// Make it the same size as the image
canvas.width = slideshow.width;
canvas.height = slideshow.height;
// Drawing the default version of the image on the canvas:
canvasContext.drawImage(image,0,0);
// Taking the image data and storing it in the imageData array:
var imageData = canvasContext.getImageData(0,0,canvas.width,canvas.height),
data = imageData.data;
// Loop through all the pixels in the imageData array, and modify
// the red, green, and blue color values.
for(var i = 0,z=data.length;i<z;i++){
// The values for red, green and blue are consecutive elements
// in the imageData array. We modify the three of them at once:
data[i] = ((data[i] < 128) ? (2*data[i]*data[i] / 255) :
(255 - 2 * (255 - data[i]) * (255 - data[i]) / 255));
data[++i] = ((data[i] < 128) ? (2*data[i]*data[i] / 255) :
(255 - 2 * (255 - data[i]) * (255 - data[i]) / 255));
data[++i] = ((data[i] < 128) ? (2*data[i]*data[i] / 255) :
(255 - 2 * (255 - data[i]) * (255 - data[i]) / 255));
// After the RGB channels comes the alpha value, which we leave the same.
++i;
}
// Putting the modified imageData back on the canvas.
canvasContext.putImageData(imageData,0,0,0,0,imageData.width,imageData.height);
// Inserting the canvas in the DOM, before the image:
image.parentNode.insertBefore(canvas, image);
}
});
</script>
CSS
/*canvas slide show*/
#slideshow{
background-color:#F5F5F5;
border:1px solid #FFFFFF;
height:250px;
margin:10px auto 0;
position:relative;
width:640px;
-moz-box-shadow:0 0 22px #111;
-webkit-box-shadow:0 0 22px #111;
box-shadow:0 0 22px #111;
}
#slideshow ul{
height:220px;
left:10px;
list-style:none outside none;
overflow:hidden;
position:absolute;
top:10px;
width:620px;
}
#slideshow li{
position:absolute;
display:none;
z-index:10;
}
#slideshow li:first-child{
display:block;
z-index:1000;
}
#slideshow .slideActive{
z-index:1000;
}
#slideshow canvas{
display:none;
position:absolute;
z-index:100;
}
#slideshow .arrow{
height:86px;
width:60px;
position:absolute;
background:url('/images/arrows.png') no-repeat;
top:50%;
margin-top:-43px;
cursor:pointer;
z-index:5000;
}
#slideshow .previous{ background-position:left top;left:0;}
#slideshow .previous:hover{ background-position:left bottom;}
#slideshow .next{ background-position:right top;right:0;}
#slideshow .next:hover{ background-position:right bottom;}
dottDesign/Auto Height iFrame ( Other)
Use this javascript function in your frame page..
"
function resizeIframe(iframeID) {
if(self==parent) return false; /* Checks that page is in iframe. */
else if(document.getElementById&&document.all) /* Sniffs for IE5+.*/
var FramePageHeight = framePage.scrollHeight + 10; /* framePage
is the ID of the framed page's BODY tag. The added 10 pixels prevent an
unnecessary scrollbar. */
parent.document.getElementById(iframeID).style.height=FramePageHeight;
/* "iframeID" is the ID of the inline frame in the parent page. */
}
"
and run it on load
"<body id="framePage" onload="resizeIframe('idTopFrame')">"
rfeldmesser/resize bitmapdata ( ActionScript 3)
public static function resizeBitmapData(bmp: BitmapData, _tileSize:int):BitmapData
{
var image : mx.controls.Image = new mx.controls.Image();
image.load (new Bitmap (bmp, "auto", true));
var ratio:Number;
if(image.content.width>image.content.height)
{
ratio = _tileSize/image.content.width;
}
if(image.content.width<image.content.height)
{
ratio = _tileSize/image.content.height;
}
image.content.width *= ratio;
image.content.height *= ratio;
return BitmapUtil.getSnapshot(image);
}
This snippet uses the BitmapUtil to resize bitmap data, whilst maintaining transparency and aspect ratio, It assumes that you want a square output, so for those of you who want resizing rectangular images, just make the "ratio" part handle both X and Y.
cheers.
Prasad Upasani/AutoSizeGrid ( VB.NET)
' Automatically autosize datgrid columns
Public Sub AutoSizeGrid(ByVal dgData As DataGrid, Optional ByVal minWidth As Integer = 0)
Dim gr As Graphics
Dim rowCount As Integer
Try
If IsNothing(dgData) OrElse (Not dgData.Visible) OrElse IsNothing(dgData.DataSource) OrElse dgData.TableStyles.Count = 0 Then
' No data to resize, exit silently
Exit Sub
End If
rowCount = dgData.VisibleRowCount
' Don't change size if there are no rows.
If rowCount = 0 Then
Exit Sub
End If
Catch e As Exception
' Ignore
End Try
Try
Dim dcCol As DataColumn
Dim sngHdrPad, sngDataPad As Single
Dim rowNum, colNum As Integer
Dim intPadding As Integer = 1
Dim dgc As DataGridColumnStyle
dgData.BeginInit() ' Tell .NET to hold off on displaying the datagrid till we are done
Dim sz As SizeF 'Stores an ordered pair of floating-point numbers, typically the width and height of a rectangle.
gr = dgData.CreateGraphics
sz = gr.MeasureString(New String("M", intPadding), dgData.HeaderFont) ' Pad "n" M-width characters
sngHdrPad = sz.Width
sz = gr.MeasureString(New String("M", intPadding), dgData.Font) ' Pad "n" M-width characters
sngDataPad = sz.Width
' Loop through the column header in the bound DataTable
For Each dgc In dgData.TableStyles(0).GridColumnStyles
If TypeOf dgc Is DataGridTextBoxColumn Then
' Measure the "width" of the text in each grid column header
sz = gr.MeasureString(dgc.HeaderText, dgData.HeaderFont)
dgc.Width = Math.Max(sz.Width + sngHdrPad, minWidth)
End If
Next
' Iterate through data rows
For rowNum = 0 To rowCount - 1
' Loop through each column
colNum = 0
For Each dgc In dgData.TableStyles(0).GridColumnStyles
If TypeOf dgc Is DataGridTextBoxColumn Then
' Measure "width" of data value
sz = gr.MeasureString(dgData(rowNum, colNum).ToString, dgData.Font)
' Use larger of header and data width
dgc.Width = Math.Max(sz.Width + sngDataPad, dgc.Width)
End If
colNum += 1
Next dgc
Next rowNum
Catch ex As Exception
MessageBox.Show("Error resizing datagrid: " & vbCrLf & ex.Message, "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error)
Finally
Try
dgData.EndInit() ' complete graphics edit
gr.Dispose() ' Release graphic object
Catch e As Exception
End Try
End Try
End Sub
Automatically autosize datgrid columns
volvis/Canvas image scale 2x w/o anti-alias in Chrome ( JavaScript)
var targetContext = targetCanvas.getContext("2d")
var h, w, hV = virtualCanvas.height, wV = virtualCanvas.width, h2, w2
for (h = 0; h < hV; h++) {
h2 = h * 2
for (w = 0; w < wV; w++) {
w2 = w * 2
targetContext.drawImage( this.virtualCanvas, w, h, 1, 1, w2, h2, 2, 2 )
}
}
Somewhere along the road the people behind canvas decided that all image scaling is anti-aliased by default. Firefox has 'mozImageSmoothingEnabled' while Chrome et company don't.
This is a proof of concept script to resize 'virtualCanvas' two times and draw it on 'targetCanvas' w/o any antialiasing.
Proof of concept in that it still takes too long to compute in real time. - Firefox: 1ms with native antialiasing off - Chrome: 45ms with the script below
It might be useful to use this to scale assets before doing any compositioning. Like, load images, scale them up, position everything times two... But if yer planning to composite the canvas first and scale that to fit as the last step, I'd advice against it..
depiction/Facebook iFrame Auto Height ( JavaScript)
<script src="http://connect.facebook.net/en_US/all.js" type="text/javascript"></script>
<script type="text/javascript">
FB.init({
appId : 'APP ID GOES HERE',
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : false // parse XFBML
});
FB.Canvas.setAutoResize( 100 );
</script>
[CODING HERE]
<script type="text/javascript">
FB.Canvas.setAutoResize( 100 );
</script>
</body>
karlhorky/AutoHotkey: NiftyWindows Mod ( Other)
/*
* Copyright (c) 2004-2005 by Enovatic-Solutions. All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
* ----------------------------------------------------------------------
* If you have any suggestions of new features or further questions
* feel free to contact the author.
*
* Company: Enovatic-Solutions (IT Service Provider)
* Author: Oliver Pfeiffer, Bremen (GERMANY)
* Homepage: http://www.enovatic.org/
* Email: contact@enovatic.org
*/
; NiftyWindows Version 0.9.3.1
; http://www.enovatic.org/products/niftywindows/
; AutoHotkey Version 1.0.36.01
; http://www.autohotkey.com/
#SingleInstance force
#HotkeyInterval 1000
#MaxHotkeysPerInterval 100
#NoTrayIcon
; [SYS] autostart section
SplitPath, A_ScriptFullPath, SYS_ScriptNameExt, SYS_ScriptDir, SYS_ScriptExt, SYS_ScriptNameNoExt, SYS_ScriptDrive
SYS_ScriptVersion = 0.9.3.1
SYS_ScriptBuild = 20050702195845
SYS_ScriptInfo = %SYS_ScriptNameNoExt% %SYS_ScriptVersion%
Process, Priority, , HIGH
SetBatchLines, -1
; TODO : a nulled key delay may produce problems for WinAmp control
SetKeyDelay, 0, 0
SetMouseDelay, 0
SetDefaultMouseSpeed, 0
SetWinDelay, 0
SetControlDelay, 0
Gosub, SYS_ParseCommandLine
Gosub, CFG_LoadSettings
Gosub, CFG_ApplySettings
MIR_MirandaFullPath = %ProgramFiles%\Miranda\Miranda32.exe
SplitPath, MIR_MirandaFullPath, , MIR_MirandaDir
if ( !A_IsCompiled )
SetTimer, REL_ScriptReload, 1000
OnExit, SYS_ExitHandler
Gosub, TRY_TrayInit
Gosub, SYS_ContextCheck
Gosub, UPD_AutoCheckForUpdate
Return
; [SYS] parses command line parameters
SYS_ParseCommandLine:
Loop %0%
If ( (%A_Index% = "/x") or (%A_Index% = "/exit") )
ExitApp
Return
; [SYS] exit handler
SYS_ExitHandler:
Gosub, AOT_ExitHandler
Gosub, ROL_ExitHandler
Gosub, TRA_ExitHandler
Gosub, CFG_SaveSettings
ExitApp
; [SYS] context check
SYS_ContextCheck:
Gosub, SYS_TrayTipBalloonCheck
If ( !SYS_TrayTipBalloon )
{
Gosub, SUS_SuspendSaveState
Suspend, On
MsgBox, 4148, Balloon Handler - %SYS_ScriptInfo%, The balloon messages are disabled on your system. These visual messages`nabove the system tray are often used by tools as additional information four`nyour interest.`n`nNiftyWindows uses balloon messages to show you some important operating`ndetails. If you leave the messages disabled NiftyWindows will show some plain`nmessages as tooltips instead (in front of the system tray).`n`nDo you want to enable balloon messages now (highly recommended)?
Gosub, SUS_SuspendRestoreState
IfMsgBox, Yes
{
SYS_TrayTipBalloon = 1
RegWrite, REG_DWORD, HKEY_CURRENT_USER, Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced, EnableBalloonTips, %SYS_TrayTipBalloon%
RegWrite, REG_DWORD, HKEY_LOCAL_MACHINE, Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced, EnableBalloonTips, %SYS_TrayTipBalloon%
SendMessage, 0x001A, , , , ahk_id 0xFFFF ; 0x001A is WM_SETTINGCHANGE ; 0xFFFF is HWND_BROADCAST
Sleep, 500 ; lets the other windows relax
}
}
IfNotExist, %A_ScriptDir%\readme.txt
{
TRY_TrayEvent := "Help"
Gosub, TRY_TrayEvent
Suspend, On
Sleep, 10000
ExitApp, 1
}
IfNotExist, %A_ScriptDir%\license.txt
{
TRY_TrayEvent := "View License"
Gosub, TRY_TrayEvent
Suspend, On
Sleep, 10000
ExitApp, 1
}
TRY_TrayEvent := "About"
Gosub, TRY_TrayEvent
Return
; [SYS] handles tooltips
SYS_ToolTipShow:
If ( SYS_ToolTipText )
{
If ( !SYS_ToolTipSeconds )
SYS_ToolTipSeconds = 2
SYS_ToolTipMillis := SYS_ToolTipSeconds * 1000
CoordMode, Mouse, Screen
CoordMode, ToolTip, Screen
If ( !SYS_ToolTipX or !SYS_ToolTipY )
{
MouseGetPos, SYS_ToolTipX, SYS_ToolTipY
SYS_ToolTipX += 16
SYS_ToolTipY += 24
}
ToolTip, %SYS_ToolTipText%, %SYS_ToolTipX%, %SYS_ToolTipY%
SetTimer, SYS_ToolTipHandler, %SYS_ToolTipMillis%
}
SYS_ToolTipText =
SYS_ToolTipSeconds =
SYS_ToolTipX =
SYS_ToolTipY =
Return
SYS_ToolTipFeedbackShow:
If ( SYS_ToolTipFeedback )
Gosub, SYS_ToolTipShow
SYS_ToolTipText =
SYS_ToolTipSeconds =
SYS_ToolTipX =
SYS_ToolTipY =
Return
SYS_ToolTipHandler:
SetTimer, SYS_ToolTipHandler, Off
ToolTip
Return
; [SYS] handles balloon messages
SYS_TrayTipShow:
If ( SYS_TrayTipText )
{
If ( !SYS_TrayTipTitle )
SYS_TrayTipTitle = %SYS_ScriptInfo%
If ( !SYS_TrayTipSeconds )
SYS_TrayTipSeconds = 10
If ( !SYS_TrayTipOptions )
SYS_TrayTipOptions = 17
SYS_TrayTipMillis := SYS_TrayTipSeconds * 1000
Gosub, SYS_TrayTipBalloonCheck
If ( SYS_TrayTipBalloon and !A_IconHidden )
{
TrayTip, %SYS_TrayTipTitle%, %SYS_TrayTipText%, %SYS_TrayTipSeconds%, %SYS_TrayTipOptions%
SetTimer, SYS_TrayTipHandler, %SYS_TrayTipMillis%
}
Else
{
TrayTip
SYS_ToolTipText = %SYS_TrayTipTitle%:`n`n%SYS_TrayTipText%
SYS_ToolTipSeconds = %SYS_TrayTipSeconds%
SysGet, SYS_TrayTipDisplay, Monitor
SYS_ToolTipX = %SYS_TrayTipDisplayRight%
SYS_ToolTipY = %SYS_TrayTipDisplayBottom%
Gosub, SYS_ToolTipShow
}
}
SYS_TrayTipTitle =
SYS_TrayTipText =
SYS_TrayTipSeconds =
SYS_TrayTipOptions =
Return
SYS_TrayTipHandler:
SetTimer, SYS_TrayTipHandler, Off
TrayTip
Return
SYS_TrayTipBalloonCheck:
RegRead, SYS_TrayTipBalloonCU, HKEY_CURRENT_USER, Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced, EnableBalloonTips
SYS_TrayTipBalloonCU := ErrorLevel or SYS_TrayTipBalloonCU
RegRead, SYS_TrayTipBalloonLM, HKEY_LOCAL_MACHINE, Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced, EnableBalloonTips
SYS_TrayTipBalloonLM := ErrorLevel or SYS_TrayTipBalloonLM
SYS_TrayTipBalloon := SYS_TrayTipBalloonCU and SYS_TrayTipBalloonLM
Return
; [SUS] provides suspend services
#Esc::
SUS_SuspendToggle:
Suspend, Permit
If ( !A_IsSuspended )
{
Suspend, On
SYS_TrayTipText = NiftyWindows is suspended now.`nPress WIN+ESC to resume it again.
SYS_TrayTipOptions = 2
}
Else
{
Suspend, Off
SYS_TrayTipText = NiftyWindows is resumed now.`nPress WIN+ESC to suspend it again.
}
Gosub, SYS_TrayTipShow
Gosub, TRY_TrayUpdate
Return
SUS_SuspendSaveState:
SUS_Suspended := A_IsSuspended
Return
SUS_SuspendRestoreState:
If ( SUS_Suspended )
Suspend, On
Else
Suspend, Off
Return
SUS_SuspendHandler:
IfWinActive, A
{
WinGet, SUS_WinID, ID
If ( !SUS_WinID )
Return
WinGet, SUS_WinMinMax, MinMax, ahk_id %SUS_WinID%
WinGetPos, SUS_WinX, SUS_WinY, SUS_WinW, SUS_WinH, ahk_id %SUS_WinID%
If ( (SUS_WinMinMax = 0) and (SUS_WinX = 0) and (SUS_WinY = 0) and (SUS_WinW = A_ScreenWidth) and (SUS_WinH = A_ScreenHeight) )
{
WinGetClass, SUS_WinClass, ahk_id %SUS_WinID%
WinGet, SUS_ProcessName, ProcessName, ahk_id %SUS_WinID%
SplitPath, SUS_ProcessName, , , SUS_ProcessExt
If ( (SUS_WinClass != "Progman") and (SUS_ProcessExt != "scr") and !SUS_FullScreenSuspend )
{
SUS_FullScreenSuspend = 1
SUS_FullScreenSuspendState := A_IsSuspended
If ( !A_IsSuspended )
{
Suspend, On
SYS_TrayTipText = A full screen window was activated.`nNiftyWindows is suspended now.`nPress WIN+ESC to resume it again.
SYS_TrayTipOptions = 2
Gosub, SYS_TrayTipShow
Gosub, TRY_TrayUpdate
}
}
}
Else
{
If ( SUS_FullScreenSuspend )
{
SUS_FullScreenSuspend = 0
If ( A_IsSuspended and !SUS_FullScreenSuspendState )
{
Suspend, Off
SYS_TrayTipText = A full screen window was deactivated.`nNiftyWindows is resumed now.`nPress WIN+ESC to suspend it again.
Gosub, SYS_TrayTipShow
Gosub, TRY_TrayUpdate
}
}
}
}
Return
; [SYS] provides reversion of all visual effects
/**
* This powerful hotkey removes all visual effects (like on exit) that have
* been made before by NiftyWindows. You can use this action as a fall-back
* solution to quickly revert any always-on-top, rolled windows and
* transparency features you've set before.
*/
^#BS::
^!BS::
SYS_RevertVisualEffects:
Gosub, AOT_SetAllOff
Gosub, ROL_RollDownAll
Gosub, TRA_TransparencyAllOff
SYS_TrayTipText = All visual effects (AOT, Roll, Transparency) were reverted.
Gosub, SYS_TrayTipShow
Return
; [NWD] nifty window dragging
/**
* This is the most powerful feature of NiftyWindows. The area of every window
* is tiled in a virtual 9-cell grid with three columns and rows. The center
* cell is the largest one and you can grab and move a window around by clicking
* and holding it with the right mouse button. The other eight corner cells are
* used to resize a resizable window in the same manner.
*/
$RButton::
$+RButton::
$+!RButton::
$+^RButton::
$+#RButton::
$+!^RButton::
$+!#RButton::
$+^#RButton::
$+!^#RButton::
$!RButton::
$!^RButton::
$!#RButton::
$!^#RButton::
$^RButton::
$^#RButton::
$#RButton::
NWD_ResizeGrids = 5
CoordMode, Mouse, Screen
MouseGetPos, NWD_MouseStartX, NWD_MouseStartY, NWD_WinID
If ( !NWD_WinID )
Return
WinGetPos, NWD_WinStartX, NWD_WinStartY, NWD_WinStartW, NWD_WinStartH, ahk_id %NWD_WinID%
WinGet, NWD_WinMinMax, MinMax, ahk_id %NWD_WinID%
WinGet, NWD_WinStyle, Style, ahk_id %NWD_WinID%
WinGetClass, NWD_WinClass, ahk_id %NWD_WinID%
GetKeyState, NWD_CtrlState, Ctrl, P
; the and'ed condition checks for popup window:
; (WS_POPUP) and !(WS_DLGFRAME | WS_SYSMENU | WS_THICKFRAME)
If ( (NWD_WinClass = "Progman") or ((NWD_CtrlState = "U") and (((NWD_WinStyle & 0x80000000) and !(NWD_WinStyle & 0x4C0000)) or (NWD_WinClass = "ExploreWClass") or (NWD_WinClass = "CabinetWClass") or (NWD_WinClass = "IEFrame") or (NWD_WinClass = "MozillaWindowClass") or (NWD_WinClass = "OpWindow") or (NWD_WinClass = "ATL:ExplorerFrame") or (NWD_WinClass = "ATL:ScrapFrame"))) )
{
NWD_ImmediateDownRequest = 1
NWD_ImmediateDown = 0
NWD_PermitClick = 1
}
Else
{
NWD_ImmediateDownRequest = 0
NWD_ImmediateDown = 0
NWD_PermitClick = 1
}
NWD_Dragging := (NWD_WinClass != "Progman") and ((NWD_CtrlState = "D") or ((NWD_WinMinMax != 1) and !NWD_ImmediateDownRequest))
; checks wheter the window has a sizing border (WS_THICKFRAME)
If ( (NWD_CtrlState = "D") or (NWD_WinStyle & 0x40000) )
{
If ( (NWD_MouseStartX >= NWD_WinStartX + NWD_WinStartW / NWD_ResizeGrids) and (NWD_MouseStartX <= NWD_WinStartX + (NWD_ResizeGrids - 1) * NWD_WinStartW / NWD_ResizeGrids) )
NWD_ResizeX = 0
Else
If ( NWD_MouseStartX > NWD_WinStartX + NWD_WinStartW / 2 )
NWD_ResizeX := 1
Else
NWD_ResizeX := -1
If ( (NWD_MouseStartY >= NWD_WinStartY + NWD_WinStartH / NWD_ResizeGrids) and (NWD_MouseStartY <= NWD_WinStartY + (NWD_ResizeGrids - 1) * NWD_WinStartH / NWD_ResizeGrids) )
NWD_ResizeY = 0
Else
If ( NWD_MouseStartY > NWD_WinStartY + NWD_WinStartH / 2 )
NWD_ResizeY := 1
Else
NWD_ResizeY := -1
}
Else
{
NWD_ResizeX = 0
NWD_ResizeY = 0
}
If ( NWD_WinStartW and NWD_WinStartH )
NWD_WinStartAR := NWD_WinStartW / NWD_WinStartH
Else
NWD_WinStartAR = 0
; TODO : this is a workaround (checks for popup window) for the activation
; bug of AutoHotkey -> can be removed as soon as the known bug is fixed
If ( !((NWD_WinStyle & 0x80000000) and !(NWD_WinStyle & 0x4C0000)) )
IfWinNotActive, ahk_id %NWD_WinID%
WinActivate, ahk_id %NWD_WinID%
; TODO : the hotkeys must be enabled in the 2nd block because the 1st block
; activates them only for the first call (historical problem of AutoHotkey)
Hotkey, Shift, NWD_IgnoreKeyHandler
Hotkey, Ctrl, NWD_IgnoreKeyHandler
Hotkey, Alt, NWD_IgnoreKeyHandler
Hotkey, LWin, NWD_IgnoreKeyHandler
Hotkey, RWin, NWD_IgnoreKeyHandler
Hotkey, Shift, On
Hotkey, Ctrl, On
Hotkey, Alt, On
Hotkey, LWin, On
Hotkey, RWin, On
SetTimer, NWD_IgnoreKeyHandler, 100
SetTimer, NWD_WindowHandler, 10
Return
NWD_SetDraggingOff:
NWD_Dragging = 0
Return
NWD_SetClickOff:
NWD_PermitClick = 0
NWD_ImmediateDownRequest = 0
Return
NWD_SetAllOff:
Gosub, NWD_SetDraggingOff
Gosub, NWD_SetClickOff
Return
NWD_IgnoreKeyHandler:
GetKeyState, NWD_RButtonState, RButton, P
GetKeyState, NWD_ShiftState, Shift, P
GetKeyState, NWD_CtrlState, Ctrl, P
GetKeyState, NWD_AltState, Alt, P
; TODO : unlike the other modifiers, Win does not exist
; as a virtual key (but Ctrl, Alt and Shift do)
GetKeyState, NWD_LWinState, LWin, P
GetKeyState, NWD_RWinState, RWin, P
If ( (NWD_LWinState = "D") or (NWD_RWinState = "D") )
NWD_WinState = D
Else
NWD_WinState = U
If ( (NWD_RButtonState = "U") and (NWD_ShiftState = "U") and (NWD_CtrlState = "U") and (NWD_AltState = "U") and (NWD_WinState = "U") )
{
SetTimer, NWD_IgnoreKeyHandler, Off
Hotkey, Shift, Off
Hotkey, Ctrl, Off
Hotkey, Alt, Off
Hotkey, LWin, Off
Hotkey, RWin, Off
}
Return
NWD_WindowHandler:
SetWinDelay, -1
CoordMode, Mouse, Screen
MouseGetPos, NWD_MouseX, NWD_MouseY
WinGetPos, NWD_WinX, NWD_WinY, NWD_WinW, NWD_WinH, ahk_id %NWD_WinID%
GetKeyState, NWD_RButtonState, RButton, P
GetKeyState, NWD_ShiftState, Shift, P
GetKeyState, NWD_AltState, Alt, P
; TODO : unlike the other modifiers, Win does not exist
; as a virtual key (but Ctrl, Alt and Shift do)
GetKeyState, NWD_LWinState, LWin, P
GetKeyState, NWD_RWinState, RWin, P
If ( (NWD_LWinState = "D") or (NWD_RWinState = "D") )
NWD_WinState = D
Else
NWD_WinState = U
If ( NWD_RButtonState = "U" )
{
SetTimer, NWD_WindowHandler, Off
If ( NWD_ImmediateDown )
MouseClick, RIGHT, %NWD_MouseX%, %NWD_MouseY%, , , U
Else
If ( NWD_PermitClick and (!NWD_Dragging or ((NWD_MouseStartX = NWD_MouseX) and (NWD_MouseStartY = NWD_MouseY))) )
{
MouseClick, RIGHT, %NWD_MouseStartX%, %NWD_MouseStartY%, , , D
MouseClick, RIGHT, %NWD_MouseX%, %NWD_MouseY%, , , U
}
Gosub, NWD_SetAllOff
NWD_ImmediateDown = 0
}
Else
{
NWD_MouseDeltaX := NWD_MouseX - NWD_MouseStartX
NWD_MouseDeltaY := NWD_MouseY - NWD_MouseStartY
If ( NWD_MouseDeltaX or NWD_MouseDeltaY )
{
If ( NWD_ImmediateDownRequest and !NWD_ImmediateDown )
{
MouseClick, RIGHT, %NWD_MouseStartX%, %NWD_MouseStartY%, , , D
MouseMove, %NWD_MouseX%, %NWD_MouseY%
NWD_ImmediateDown = 1
NWD_PermitClick = 0
}
If ( NWD_Dragging )
{
If ( !NWD_ResizeX and !NWD_ResizeY )
{
NWD_WinNewX := NWD_WinStartX + NWD_MouseDeltaX
NWD_WinNewY := NWD_WinStartY + NWD_MouseDeltaY
NWD_WinNewW := NWD_WinStartW
NWD_WinNewH := NWD_WinStartH
}
Else
{
NWD_WinDeltaW = 0
NWD_WinDeltaH = 0
If ( NWD_ResizeX )
NWD_WinDeltaW := NWD_ResizeX * NWD_MouseDeltaX
If ( NWD_ResizeY )
NWD_WinDeltaH := NWD_ResizeY * NWD_MouseDeltaY
If ( NWD_WinState = "D" )
{
If ( NWD_ResizeX )
NWD_WinDeltaW *= 2
If ( NWD_ResizeY )
NWD_WinDeltaH *= 2
}
NWD_WinNewW := NWD_WinStartW + NWD_WinDeltaW
NWD_WinNewH := NWD_WinStartH + NWD_WinDeltaH
If ( NWD_WinNewW < 0 )
If ( NWD_WinState = "D" )
NWD_WinNewW *= -1
Else
NWD_WinNewW := 0
If ( NWD_WinNewH < 0 )
If ( NWD_WinState = "D" )
NWD_WinNewH *= -1
Else
NWD_WinNewH := 0
If ( (NWD_AltState = "D") and NWD_WinStartAR )
{
NWD_WinNewARW := NWD_WinNewH * NWD_WinStartAR
NWD_WinNewARH := NWD_WinNewW / NWD_WinStartAR
If ( NWD_WinNewW < NWD_WinNewARW )
NWD_WinNewW := NWD_WinNewARW
If ( NWD_WinNewH < NWD_WinNewARH )
NWD_WinNewH := NWD_WinNewARH
}
NWD_WinDeltaX = 0
NWD_WinDeltaY = 0
If ( NWD_WinState = "D" )
{
NWD_WinDeltaX := NWD_WinStartW / 2 - NWD_WinNewW / 2
NWD_WinDeltaY := NWD_WinStartH / 2 - NWD_WinNewH / 2
}
Else
{
If ( NWD_ResizeX = -1 )
NWD_WinDeltaX := NWD_WinStartW - NWD_WinNewW
If ( NWD_ResizeY = -1 )
NWD_WinDeltaY := NWD_WinStartH - NWD_WinNewH
}
NWD_WinNewX := NWD_WinStartX + NWD_WinDeltaX
NWD_WinNewY := NWD_WinStartY + NWD_WinDeltaY
}
If ( NWD_ShiftState = "D" )
NWD_WinNewRound = -1
Else
NWD_WinNewRound = 0
Transform, NWD_WinNewX, Round, %NWD_WinNewX%, %NWD_WinNewRound%
Transform, NWD_WinNewY, Round, %NWD_WinNewY%, %NWD_WinNewRound%
Transform, NWD_WinNewW, Round, %NWD_WinNewW%, %NWD_WinNewRound%
Transform, NWD_WinNewH, Round, %NWD_WinNewH%, %NWD_WinNewRound%
If ( (NWD_WinNewX != NWD_WinX) or (NWD_WinNewY != NWD_WinY) or (NWD_WinNewW != NWD_WinW) or (NWD_WinNewH != NWD_WinH) )
{
WinMove, ahk_id %NWD_WinID%, , %NWD_WinNewX%, %NWD_WinNewY%, %NWD_WinNewW%, %NWD_WinNewH%
If ( SYS_ToolTipFeedback )
{
WinGetPos, NWD_ToolTipWinX, NWD_ToolTipWinY, NWD_ToolTipWinW, NWD_ToolTipWinH, ahk_id %NWD_WinID%
SYS_ToolTipText = Window Drag: (X:%NWD_ToolTipWinX%, Y:%NWD_ToolTipWinY%, W:%NWD_ToolTipWinW%, H:%NWD_ToolTipWinH%)
Gosub, SYS_ToolTipFeedbackShow
}
}
}
}
}
Return
; [MIW {NWD}] minimize/roll on right + left mouse button
/**
* Minimizes the selected window (if minimizable) to the task bar. If you press
* the left button over the titlebar the selected window will be rolled up
* instead of being minimized. You have to apply this action again to roll the
* window back down.
*/
$LButton::
$^LButton::
GetKeyState, MIW_RButtonState, RButton, P
If ( (MIW_RButtonState = "D") and (!NWD_ImmediateDown) and (NWD_WinClass != "Progman") )
{
GetKeyState, MIW_CtrlState, Ctrl, P
WinGet, MIW_WinStyle, Style, ahk_id %NWD_WinID%
SysGet, MIW_CaptionHeight, 4 ; SM_CYCAPTION
SysGet, MIW_BorderHeight, 7 ; SM_CXDLGFRAME
MouseGetPos, , MIW_MouseY
If ( MIW_MouseY <= MIW_CaptionHeight + MIW_BorderHeight )
{
; checks wheter the window has a sizing border (WS_THICKFRAME)
If ( (MIW_CtrlState = "D") or (MIW_WinStyle & 0x40000) )
{
Gosub, NWD_SetAllOff
ROL_WinID = %NWD_WinID%
Gosub, ROL_RollToggle
}
}
Else
{
; the second condition checks for minimizable window:
; (WS_CAPTION | WS_SYSMENU | WS_MINIMIZEBOX)
If ( (MIW_CtrlState = "D") or (MIW_WinStyle & 0xCA0000 = 0xCA0000) )
{
Gosub, NWD_SetAllOff
WinMinimize, ahk_id %NWD_WinID%
SYS_ToolTipText = Window Minimize
Gosub, SYS_ToolTipFeedbackShow
}
}
}
Else
{
; this feature should be implemented by using a timer because
; AutoHotkeys threading blocks the first thread if another
; one is started (until the 2nd is stopped)
Thread, priority, 1
MouseClick, LEFT, , , , , D
KeyWait, LButton
MouseClick, LEFT, , , , , U
}
Return
; [CLW {NWD}] close/send bottom on right + middle mouse button || double click on middle mouse button
/**
* Closes the selected window (if closeable) as if you click the close button
* in the titlebar. If you press the middle button over the titlebar the
* selected window will be sent to the bottom of the window stack instead of
* being closed.
*
* Edited Aug 6, 2010 by Karl Horky to add clickthrough if not over title bar area or right mouse button held
*/
$MButton::
$^MButton::
SetBatchLines, -1
CoordMode, Mouse, Screen
SetMouseDelay, -1 ; no pause after mouse clicks
SetKeyDelay, -1 ; no pause after keys sent
MouseGetPos, ClickX, ClickY, WindowUnderMouseID
WinActivate, ahk_id %WindowUnderMouseID%
; WM_NCHITTEST
SendMessage, 0x84,, ( ClickY << 16 )|ClickX,, ahk_id %WindowUnderMouseID%
WM_NCHITTEST_Result =%ErrorLevel%
/*
#define HTERROR (-2)
#define HTTRANSPARENT (-1)
#define HTNOWHERE 0
#define HTCLIENT 1
#define HTCAPTION 2
#define HTSYSMENU 3
#define HTGROWBOX 4
#define HTSIZE HTGROWBOX
#define HTMENU 5
#define HTHSCROLL 6
#define HTVSCROLL 7
#define HTMINBUTTON 8
#define HTMAXBUTTON 9
#define HTLEFT 10
#define HTRIGHT 11
#define HTTOP 12
#define HTTOPLEFT 13
#define HTTOPRIGHT 14
#define HTBOTTOM 15
#define HTBOTTOMLEFT 16
#define HTBOTTOMRIGHT 17
#define HTBORDER 18
#define HTREDUCE HTMINBUTTON
#define HTZOOM HTMAXBUTTON
#define HTSIZEFIRST HTLEFT
#define HTSIZELAST HTBOTTOMRIGHT
#if(WINVER >= 0x0400)
#define HTOBJECT 19
#define HTCLOSE 20
#define HTHELP 21
*/
GetKeyState, CLW_RButtonState, RButton, P
If ( (CLW_RButtonState = "D") and (!NWD_ImmediateDown) and (NWD_WinClass != "Progman") )
{
GetKeyState, CLW_CtrlState, Ctrl, P
WinGet, CLW_WinStyle, Style, ahk_id %NWD_WinID%
SysGet, CLW_CaptionHeight, 4 ; SM_CYCAPTION
SysGet, CLW_BorderHeight, 7 ; SM_CXDLGFRAME
MouseGetPos, , CLW_MouseY
If ( CLW_MouseY <= CLW_CaptionHeight + CLW_BorderHeight )
{
Gosub, NWD_SetAllOff
Send, !{Esc}
SYS_ToolTipText = Window Bottom
Gosub, SYS_ToolTipFeedbackShow
}
Else
{
; the second condition checks for closeable window:
; (WS_CAPTION | WS_SYSMENU)
If ( (CLW_CtrlState = "D") or (CLW_WinStyle & 0xC80000 = 0xC80000) )
{
Gosub, NWD_SetAllOff
WinClose, ahk_id %NWD_WinID%
SYS_ToolTipText = Window Close
Gosub, SYS_ToolTipFeedbackShow
}
}
}
; Close window with titlebar click
Else If WM_NCHITTEST_Result in 2,3,8,9,20,21 ; in titlebar enclosed area - top of window
{
IfWinNotActive, ahk_class Shell_TrayWnd
{
PostMessage, 0x112, 0xF060,,, ahk_id %WindowUnderMouseID% ; 0x112 = WM_SYSCOMMAND, 0xF060 = SC_CLOSE
}
Else
{
Thread, Priority, 1
MouseClick, MIDDLE, , , , , D
KeyWait, MButton
MouseClick, MIDDLE, , , , , U
}
}
Else
{
; TODO : workaround for "MouseClick, LEFT, , , 2" due to inactive titlebar problem
Thread, Priority, 1
MouseClick, MIDDLE, , , , , D
KeyWait, MButton
MouseClick, MIDDLE, , , , , U
}
Return
; [TSM {NWD}] toggles windows start menu || moves window to previous display || maximize to multiple windows on the left
/**
* This additional button is used to toggle the windows start menu.
*/
$XButton1::
$^XButton1::
If ( NWD_ImmediateDown )
Return
GetKeyState, TSM_RButtonState, RButton, P
If ( TSM_RButtonState = "U" )
{
Send, {LWin}
}
Else
IfWinActive, A
{
WinGet, TSM_WinID, ID
If ( !TSM_WinID )
Return
WinGetClass, TSM_WinClass, ahk_id %TSM_WinID%
If ( TSM_WinClass != "Progman" )
{
Gosub, NWD_SetAllOff
GetKeyState, TSM_CtrlState, Ctrl, P
If ( TSM_CtrlState = "U" )
{
Send, ^<
SYS_ToolTipText = Window Move: LEFT
Gosub, SYS_ToolTipFeedbackShow
}
; Else
; TODO : maximize to multiple displays on the left (planned feature)
}
}
Return
; [MAW {NWD}] toggles window maximizing || moves window to next display || maximize to multiple windows on the right
/**
* This additional button is used to toggle the maximize state of the active
* window (if maximizable).
*/
$XButton2::
$^XButton2::
If ( NWD_ImmediateDown )
Return
IfWinActive, A
{
WinGet, MAW_WinID, ID
If ( !MAW_WinID )
Return
WinGetClass, MAW_WinClass, ahk_id %MAW_WinID%
If ( MAW_WinClass = "Progman" )
Return
GetKeyState, MAW_RButtonState, RButton, P
If ( MAW_RButtonState = "U" )
{
GetKeyState, MAW_CtrlState, Ctrl, P
WinGet, MAW_WinStyle, Style
; the second condition checks for maximizable window:
; (WS_CAPTION | WS_SYSMENU | WS_MAXIMIZEBOX)
If ( (MAW_CtrlState = "D") or (MAW_WinStyle & 0xC90000 = 0xC90000) )
{
WinGet, MAW_MinMax, MinMax
If ( MAW_MinMax = 0 )
{
WinMaximize
SYS_ToolTipText = Window Maximize
Gosub, SYS_ToolTipFeedbackShow
}
Else
If ( MAW_MinMax = 1 )
{
WinRestore
SYS_ToolTipText = Window Restore
Gosub, SYS_ToolTipFeedbackShow
}
}
}
Else
{
Gosub, NWD_SetAllOff
GetKeyState, MAW_CtrlState, Ctrl, P
If ( MAW_CtrlState = "U" )
{
Send, ^>
SYS_ToolTipText = Window Move: RIGHT
Gosub, SYS_ToolTipFeedbackShow
}
; Else
; TODO : maximize to multiple displays on the right (planned feature)
}
}
Return
; [TSW {NWD}] provides alt-tab-menu to the right mouse button + mouse wheel
/**
* Provides a quick task switcher (alt-tab-menu) controlled by the mouse wheel.
*/
WheelDown::
GetKeyState, TSW_RButtonState, RButton, P
If ( (TSW_RButtonState = "D") and (!NWD_ImmediateDown) )
{
; TODO : this is a workaround because the original tabmenu
; code of AutoHotkey is buggy on some systems
GetKeyState, TSW_LAltState, LAlt
If ( TSW_LAltState = "U" )
{
Gosub, NWD_SetAllOff
Send, {LAlt down}{Tab}
SetTimer, TSW_WheelHandler, 1
}
Else
Send, {Tab}
}
Else
Send, {WheelDown}
Return
WheelUp::
GetKeyState, TSW_RButtonState, RButton, P
If ( (TSW_RButtonState = "D") and (!NWD_ImmediateDown) )
{
; TODO : this is a workaround because the original tabmenu
; code of AutoHotkey is buggy on some systems
GetKeyState, TSW_LAltState, LAlt
If ( TSW_LAltState = "U" )
{
Gosub, NWD_SetAllOff
Send, {LAlt down}+{Tab}
SetTimer, TSW_WheelHandler, 1
}
Else
Send, +{Tab}
}
Else
Send, {WheelUp}
Return
TSW_WheelHandler:
GetKeyState, TSW_RButtonState, RButton, P
If ( TSW_RButtonState = "U" )
{
SetTimer, TSW_WheelHandler, Off
GetKeyState, TSW_LAltState, LAlt
If ( TSW_LAltState = "D" )
Send, {LAlt up}
}
Return
; [AOT] toggles always on top
/**
* Toggles the always-on-top attribute of the selected/active window.
*/
#SC029::
#LButton::
AOT_SetToggle:
Gosub, AOT_CheckWinIDs
SetWinDelay, -1
IfInString, A_ThisHotkey, LButton
{
MouseGetPos, , , AOT_WinID
If ( !AOT_WinID )
Return
IfWinNotActive, ahk_id %AOT_WinID%
WinActivate, ahk_id %AOT_WinID%
}
IfWinActive, A
{
WinGet, AOT_WinID, ID
If ( !AOT_WinID )
Return
WinGetClass, AOT_WinClass, ahk_id %AOT_WinID%
If ( AOT_WinClass = "Progman" )
Return
WinGet, AOT_ExStyle, ExStyle, ahk_id %AOT_WinID%
If ( AOT_ExStyle & 0x8 ) ; 0x8 is WS_EX_TOPMOST
{
SYS_ToolTipText = Always on Top: OFF
Gosub, AOT_SetOff
}
Else
{
SYS_ToolTipText = Always on Top: ON
Gosub, AOT_SetOn
}
Gosub, SYS_ToolTipFeedbackShow
}
Return
AOT_SetOn:
Gosub, AOT_CheckWinIDs
SetWinDelay, -1
IfWinNotExist, ahk_id %AOT_WinID%
Return
IfNotInString, AOT_WinIDs, |%AOT_WinID%
AOT_WinIDs = %AOT_WinIDs%|%AOT_WinID%
WinSet, AlwaysOnTop, On, ahk_id %AOT_WinID%
Return
AOT_SetOff:
Gosub, AOT_CheckWinIDs
SetWinDelay, -1
IfWinNotExist, ahk_id %AOT_WinID%
Return
StringReplace, AOT_WinIDs, AOT_WinIDs, |%A_LoopField%, , All
WinSet, AlwaysOnTop, Off, ahk_id %AOT_WinID%
Return
AOT_SetAllOff:
Gosub, AOT_CheckWinIDs
Loop, Parse, AOT_WinIDs, |
If ( A_LoopField )
{
AOT_WinID = %A_LoopField%
Gosub, AOT_SetOff
}
Return
#^SC029::
Gosub, AOT_SetAllOff
SYS_ToolTipText = Always on Top: ALL OFF
Gosub, SYS_ToolTipFeedbackShow
Return
AOT_CheckWinIDs:
DetectHiddenWindows, On
Loop, Parse, AOT_WinIDs, |
If ( A_LoopField )
IfWinNotExist, ahk_id %A_LoopField%
StringReplace, AOT_WinIDs, AOT_WinIDs, |%A_LoopField%, , All
Return
AOT_ExitHandler:
Gosub, AOT_SetAllOff
Return
; [ROL] rolls up/down a window to/from its title bar
ROL_RollToggle:
Gosub, ROL_CheckWinIDs
SetWinDelay, -1
IfWinNotExist, ahk_id %ROL_WinID%
Return
WinGetClass, ROL_WinClass, ahk_id %ROL_WinID%
If ( ROL_WinClass = "Progman" )
Return
IfNotInString, ROL_WinIDs, |%ROL_WinID%
{
SYS_ToolTipText = Window Roll: UP
Gosub, ROL_RollUp
}
Else
{
WinGetPos, , , , ROL_WinHeight, ahk_id %ROL_WinID%
If ( ROL_WinHeight = ROL_WinRolledHeight%ROL_WinID% )
{
SYS_ToolTipText = Window Roll: DOWN
Gosub, ROL_RollDown
}
Else
{
SYS_ToolTipText = Window Roll: UP
Gosub, ROL_RollUp
}
}
Gosub, SYS_ToolTipFeedbackShow
Return
ROL_RollUp:
Gosub, ROL_CheckWinIDs
SetWinDelay, -1
IfWinNotExist, ahk_id %ROL_WinID%
Return
WinGetClass, ROL_WinClass, ahk_id %ROL_WinID%
If ( ROL_WinClass = "Progman" )
Return
WinGetPos, , , , ROL_WinHeight, ahk_id %ROL_WinID%
IfInString, ROL_WinIDs, |%ROL_WinID%
If ( ROL_WinHeight = ROL_WinRolledHeight%ROL_WinID% )
Return
SysGet, ROL_CaptionHeight, 4 ; SM_CYCAPTION
SysGet, ROL_BorderHeight, 7 ; SM_CXDLGFRAME
If ( ROL_WinHeight > (ROL_CaptionHeight + ROL_BorderHeight) )
{
IfNotInString, ROL_WinIDs, |%ROL_WinID%
ROL_WinIDs = %ROL_WinIDs%|%ROL_WinID%
ROL_WinOriginalHeight%ROL_WinID% := ROL_WinHeight
WinMove, ahk_id %ROL_WinID%, , , , , (ROL_CaptionHeight + ROL_BorderHeight)
WinGetPos, , , , ROL_WinRolledHeight%ROL_WinID%, ahk_id %ROL_WinID%
}
Return
ROL_RollDown:
Gosub, ROL_CheckWinIDs
SetWinDelay, -1
If ( !ROL_WinID )
Return
IfNotInString, ROL_WinIDs, |%ROL_WinID%
Return
WinGetPos, , , , ROL_WinHeight, ahk_id %ROL_WinID%
If( ROL_WinHeight = ROL_WinRolledHeight%ROL_WinID% )
WinMove, ahk_id %ROL_WinID%, , , , , ROL_WinOriginalHeight%ROL_WinID%
StringReplace, ROL_WinIDs, ROL_WinIDs, |%ROL_WinID%, , All
ROL_WinOriginalHeight%ROL_WinID% =
ROL_WinRolledHeight%ROL_WinID% =
Return
ROL_RollDownAll:
Gosub, ROL_CheckWinIDs
Loop, Parse, ROL_WinIDs, |
If ( A_LoopField )
{
ROL_WinID = %A_LoopField%
Gosub, ROL_RollDown
}
Return
#^r::
Gosub, ROL_RollDownAll
SYS_ToolTipText = Window Roll: ALL DOWN
Gosub, SYS_ToolTipFeedbackShow
Return
ROL_CheckWinIDs:
DetectHiddenWindows, On
Loop, Parse, ROL_WinIDs, |
If ( A_LoopField )
IfWinNotExist, ahk_id %A_LoopField%
{
StringReplace, ROL_WinIDs, ROL_WinIDs, |%A_LoopField%, , All
ROL_WinOriginalHeight%A_LoopField% =
ROL_WinRolledHeight%A_LoopField% =
}
Return
ROL_ExitHandler:
Gosub, ROL_RollDownAll
Return
; [TRA] provides window transparency
/**
* Adjusts the transparency of the active window in ten percent steps
* (opaque = 100%) which allows the contents of the windows behind it to shine
* through. If the window is completely transparent (0%) the window is still
* there and clickable. If you loose a transparent window it will be extremly
* complicated to find it again because it's invisible (see the first hotkey
* in this list for emergency help in such situations).
*/
#WheelUp::
#+WheelUp::
#WheelDown::
#+WheelDown::
Gosub, TRA_CheckWinIDs
SetWinDelay, -1
IfWinActive, A
{
WinGet, TRA_WinID, ID
If ( !TRA_WinID )
Return
WinGetClass, TRA_WinClass, ahk_id %TRA_WinID%
If ( TRA_WinClass = "Progman" )
Return
IfNotInString, TRA_WinIDs, |%TRA_WinID%
TRA_WinIDs = %TRA_WinIDs%|%TRA_WinID%
TRA_WinAlpha := TRA_WinAlpha%TRA_WinID%
TRA_PixelColor := TRA_PixelColor%TRA_WinID%
IfInString, A_ThisHotkey, +
TRA_WinAlphaStep := 255 * 0.01 ; 1 percent steps
Else
TRA_WinAlphaStep := 255 * 0.1 ; 10 percent steps
If ( TRA_WinAlpha = "" )
TRA_WinAlpha = 255
IfInString, A_ThisHotkey, WheelDown
TRA_WinAlpha -= TRA_WinAlphaStep
Else
TRA_WinAlpha += TRA_WinAlphaStep
If ( TRA_WinAlpha > 255 )
TRA_WinAlpha = 255
Else
If ( TRA_WinAlpha < 0 )
TRA_WinAlpha = 0
If ( !TRA_PixelColor and (TRA_WinAlpha = 255) )
{
Gosub, TRA_TransparencyOff
SYS_ToolTipText = Transparency: OFF
}
Else
{
TRA_WinAlpha%TRA_WinID% = %TRA_WinAlpha%
If ( TRA_PixelColor )
WinSet, TransColor, %TRA_PixelColor% %TRA_WinAlpha%, ahk_id %TRA_WinID%
Else
WinSet, Transparent, %TRA_WinAlpha%, ahk_id %TRA_WinID%
TRA_ToolTipAlpha := TRA_WinAlpha * 100 / 255
Transform, TRA_ToolTipAlpha, Round, %TRA_ToolTipAlpha%
SYS_ToolTipText = Transparency: %TRA_ToolTipAlpha% `%
}
Gosub, SYS_ToolTipFeedbackShow
}
Return
#^LButton::
#^MButton::
Gosub, TRA_CheckWinIDs
SetWinDelay, -1
CoordMode, Mouse, Screen
CoordMode, Pixel, Screen
MouseGetPos, TRA_MouseX, TRA_MouseY, TRA_WinID
If ( !TRA_WinID )
Return
WinGetClass, TRA_WinClass, ahk_id %TRA_WinID%
If ( TRA_WinClass = "Progman" )
Return
IfWinNotActive, ahk_id %TRA_WinID%
WinActivate, ahk_id %TRA_WinID%
IfNotInString, TRA_WinIDs, |%TRA_WinID%
TRA_WinIDs = %TRA_WinIDs%|%TRA_WinID%
IfInString, A_ThisHotkey, MButton
{
AOT_WinID = %TRA_WinID%
Gosub, AOT_SetOn
TRA_WinAlpha%TRA_WinID% := 25 * 255 / 100
}
TRA_WinAlpha := TRA_WinAlpha%TRA_WinID%
; TODO : the transparency must be set off first,
; this may be a bug of AutoHotkey
WinSet, TransColor, OFF, ahk_id %TRA_WinID%
PixelGetColor, TRA_PixelColor, %TRA_MouseX%, %TRA_MouseY%, RGB
WinSet, TransColor, %TRA_PixelColor% %TRA_WinAlpha%, ahk_id %TRA_WinID%
TRA_PixelColor%TRA_WinID% := TRA_PixelColor
IfInString, A_ThisHotkey, MButton
SYS_ToolTipText = Transparency: 25 `% + %TRA_PixelColor% color (RGB) + Always on Top
Else
SYS_ToolTipText = Transparency: %TRA_PixelColor% color (RGB)
Gosub, SYS_ToolTipFeedbackShow
Return
#MButton::
Gosub, TRA_CheckWinIDs
SetWinDelay, -1
MouseGetPos, , , TRA_WinID
If ( !TRA_WinID )
Return
IfWinNotActive, ahk_id %TRA_WinID%
WinActivate, ahk_id %TRA_WinID%
IfNotInString, TRA_WinIDs, |%TRA_WinID%
Return
Gosub, TRA_TransparencyOff
SYS_ToolTipText = Transparency: OFF
Gosub, SYS_ToolTipFeedbackShow
Return
TRA_TransparencyOff:
Gosub, TRA_CheckWinIDs
SetWinDelay, -1
If ( !TRA_WinID )
Return
IfNotInString, TRA_WinIDs, |%TRA_WinID%
Return
StringReplace, TRA_WinIDs, TRA_WinIDs, |%TRA_WinID%, , All
TRA_WinAlpha%TRA_WinID% =
TRA_PixelColor%TRA_WinID% =
; TODO : must be set to 255 first to avoid the black-colored-window problem
WinSet, Transparent, 255, ahk_id %TRA_WinID%
WinSet, TransColor, OFF, ahk_id %TRA_WinID%
WinSet, Transparent, OFF, ahk_id %TRA_WinID%
WinSet, Redraw, , ahk_id %TRA_WinID%
Return
TRA_TransparencyAllOff:
Gosub, TRA_CheckWinIDs
Loop, Parse, TRA_WinIDs, |
If ( A_LoopField )
{
TRA_WinID = %A_LoopField%
Gosub, TRA_TransparencyOff
}
Return
#^t::
Gosub, TRA_TransparencyAllOff
SYS_ToolTipText = Transparency: ALL OFF
Gosub, SYS_ToolTipFeedbackShow
Return
TRA_CheckWinIDs:
DetectHiddenWindows, On
Loop, Parse, TRA_WinIDs, |
If ( A_LoopField )
IfWinNotExist, ahk_id %A_LoopField%
{
StringReplace, TRA_WinIDs, TRA_WinIDs, |%A_LoopField%, , All
TRA_WinAlpha%A_LoopField% =
TRA_PixelColor%A_LoopField% =
}
Return
TRA_ExitHandler:
Gosub, TRA_TransparencyAllOff
Return
; [EJC] opens/closes a drive
/**
* Opens or closes an installed CD/DVD-ROM reader/writer drive tray. The drives
* are assigned to their hotkeys by the certain drive number in your system. The
* hotkeys are used in the sequence of the key placement on your physical
* keyboard from left to right (1 refers to the first and 0 to the tenth drive).
* So you are limited to a total number of 10 drives controlled by NiftyWindows.
*/
#MaxThreadsBuffer On
$#0::
$#1::
$#2::
$#3::
$#4::
$#5::
$#6::
$#7::
$#8::
$#9::
DriveGet, EJC_DriveList, List, CDROM
StringLen, EJC_DriveListLength, EJC_DriveList
StringRight, EJC_PressedDrive, A_ThisHotkey, 1
If ( !EJC_PressedDrive )
EJC_PressedDrive := 10
If ( EJC_PressedDrive <= EJC_DriveListLength )
{
StringMid, EJC_DriveLabel, EJC_DriveList, EJC_PressedDrive, 1
SYS_ToolTipText = Drive Eject: %EJC_DriveLabel%
Gosub, SYS_ToolTipFeedbackShow
Gosub, SUS_SuspendSaveState
Suspend, On
Drive, Eject, %EJC_DriveLabel%:
If ( A_TimeSinceThisHotkey < 250 )
Drive, Eject, %EJC_DriveLabel%:, 1
Gosub, SUS_SuspendRestoreState
}
Else
{
Transform, EJC_PressedDrive, Mod, %EJC_PressedDrive%, 10
Send, #%EJC_PressedDrive%
}
Return
#MaxThreadsBuffer Off
; [MUT] toggles the audio mute
/**
* Toggles the muteness of an installed audio card.
*/
Pause::
SoundSet, +1, , Mute
SoundGet, MUT_MuteState, , MUTE
SYS_ToolTipText = Audio Mute: %MUT_MuteState%
Gosub, SYS_ToolTipFeedbackShow
Return
; [SCR] starts the user defined screensaver
/**
* Starts the user defined screensaver (password protection aware).
*/
#s up::
^#s up::
RegRead, SCR_Saver, HKEY_CURRENT_USER, Control Panel\Desktop, SCRNSAVE.EXE
If ( !ErrorLevel and SCR_Saver )
{
SendMessage, 0x112, 0xF140, 0, , Program Manager ; 0x112 is WM_SYSCOMMAND ; 0xF140 is SC_SCREENSAVE
If ( A_ThisHotkey != "^#s up" )
Return
SplitPath, SCR_Saver, SCR_SaverFileName
Process, Wait, %SCR_SaverFileName%, 5
If ( ErrorLevel )
{
Gosub, SUS_SuspendSaveState
Suspend, On
Sleep, 5000
Gosub, SUS_SuspendRestoreState
Process, Exist, %SCR_SaverFileName%
If ( ErrorLevel )
SendMessage, 0x112, 0xF170, 2, , Program Manager ; 0x112 is WM_SYSCOMMAND ; 0xF170 is SC_MONITORPOWER ; (2 = off, 1 = standby, -1 = on)
}
}
Else
{
SYS_TrayTipText = No screensaver specified in display settings (control panel).
SYS_TrayTipOptions = 2
Gosub, SYS_TrayTipShow
}
Return
; [SIZ {NWD}] provides several size adjustments to windows
/**
* Adjusts the transparency of the active window in ten percent steps
* (opaque = 100%) which allows the contents of the windows behind it to shine
* through. If the window is completely transparent (0%) the window is still
* there and clickable. If you loose a transparent window it will be extremly
* complicated to find it again because it's invisible (see the first hotkey in
* this list for emergency help in such situations).
*/
!WheelUp::
!+WheelUp::
!^WheelUp::
!#WheelUp::
!+^WheelUp::
!+#WheelUp::
!^#WheelUp::
!+^#WheelUp::
!WheelDown::
!+WheelDown::
!^WheelDown::
!#WheelDown::
!+^WheelDown::
!+#WheelDown::
!^#WheelDown::
!+^#WheelDown::
; TODO : the following code block is a workaround to handle
; virtual ALT calls in WheelDown/Up functions
GetKeyState, SIZ_AltState, Alt, P
If ( SIZ_AltState = "U" )
{
IfInString, A_ThisHotkey, WheelDown
Gosub, WheelDown
Else
Gosub, WheelUp
Return
}
If ( NWD_Dragging or NWD_ImmediateDown )
Return
SetWinDelay, -1
CoordMode, Mouse, Screen
IfWinActive, A
{
WinGet, SIZ_WinID, ID
If ( !SIZ_WinID )
Return
WinGetClass, SIZ_WinClass, ahk_id %SIZ_WinID%
If ( SIZ_WinClass = "Progman" )
Return
GetKeyState, SIZ_CtrlState, Ctrl, P
WinGet, SIZ_WinMinMax, MinMax, ahk_id %SIZ_WinID%
WinGet, SIZ_WinStyle, Style, ahk_id %SIZ_WinID%
; checks wheter the window isn't maximized and has a sizing border (WS_THICKFRAME)
If ( (SIZ_CtrlState = "D") or ((SIZ_WinMinMax != 1) and (SIZ_WinStyle & 0x40000)) )
{
WinGetPos, SIZ_WinX, SIZ_WinY, SIZ_WinW, SIZ_WinH, ahk_id %SIZ_WinID%
If ( SIZ_WinW and SIZ_WinH )
{
SIZ_AspectRatio := SIZ_WinW / SIZ_WinH
IfInString, A_ThisHotkey, WheelDown
SIZ_Direction = 1
Else
SIZ_Direction = -1
IfInString, A_ThisHotkey, +
SIZ_Factor = 0.01
Else
SIZ_Factor = 0.1
SIZ_WinNewW := SIZ_WinW + SIZ_Direction * SIZ_WinW * SIZ_Factor
SIZ_WinNewH := SIZ_WinH + SIZ_Direction * SIZ_WinH * SIZ_Factor
IfInString, A_ThisHotkey, #
{
SIZ_WinNewX := SIZ_WinX + (SIZ_WinW - SIZ_WinNewW) / 2
SIZ_WinNewY := SIZ_WinY + (SIZ_WinH - SIZ_WinNewH) / 2
}
Else
{
SIZ_WinNewX := SIZ_WinX
SIZ_WinNewY := SIZ_WinY
}
If ( SIZ_WinNewW > A_ScreenWidth )
{
SIZ_WinNewW := A_ScreenWidth
SIZ_WinNewH := SIZ_WinNewW / SIZ_AspectRatio
}
If ( SIZ_WinNewH > A_ScreenHeight )
{
SIZ_WinNewH := A_ScreenHeight
SIZ_WinNewW := SIZ_WinNewH * SIZ_AspectRatio
}
Transform, SIZ_WinNewX, Round, %SIZ_WinNewX%
Transform, SIZ_WinNewY, Round, %SIZ_WinNewY%
Transform, SIZ_WinNewW, Round, %SIZ_WinNewW%
Transform, SIZ_WinNewH, Round, %SIZ_WinNewH%
WinMove, ahk_id %SIZ_WinID%, , SIZ_WinNewX, SIZ_WinNewY, SIZ_WinNewW, SIZ_WinNewH
If ( SYS_ToolTipFeedback )
{
WinGetPos, SIZ_ToolTipWinX, SIZ_ToolTipWinY, SIZ_ToolTipWinW, SIZ_ToolTipWinH, ahk_id %SIZ_WinID%
SYS_ToolTipText = Window Size: (X:%SIZ_ToolTipWinX%, Y:%SIZ_ToolTipWinY%, W:%SIZ_ToolTipWinW%, H:%SIZ_ToolTipWinH%)
Gosub, SYS_ToolTipFeedbackShow
}
}
}
}
Return
!NumpadAdd::
!^NumpadAdd::
!#NumpadAdd::
!^#NumpadAdd::
!NumpadSub::
!^NumpadSub::
!#NumpadSub::
!^#NumpadSub::
If ( NWD_Dragging or NWD_ImmediateDown )
Return
SetWinDelay, -1
CoordMode, Mouse, Screen
IfWinActive, A
{
WinGet, SIZ_WinID, ID
If ( !SIZ_WinID )
Return
WinGetClass, SIZ_WinClass, ahk_id %SIZ_WinID%
If ( SIZ_WinClass = "Progman" )
Return
GetKeyState, SIZ_CtrlState, Ctrl, P
WinGet, SIZ_WinMinMax, MinMax, ahk_id %SIZ_WinID%
WinGet, SIZ_WinStyle, Style, ahk_id %SIZ_WinID%
; checks wheter the window isn't maximized and has a sizing border (WS_THICKFRAME)
If ( (SIZ_CtrlState = "D") or ((SIZ_WinMinMax != 1) and (SIZ_WinStyle & 0x40000)) )
{
WinGetPos, SIZ_WinX, SIZ_WinY, SIZ_WinW, SIZ_WinH, ahk_id %SIZ_WinID%
IfInString, A_ThisHotkey, NumpadAdd
If ( SIZ_WinW < 160 )
SIZ_WinNewW = 160
Else
If ( SIZ_WinW < 320 )
SIZ_WinNewW = 320
Else
If ( SIZ_WinW < 640 )
SIZ_WinNewW = 640
Else
If ( SIZ_WinW < 800 )
SIZ_WinNewW = 800
Else
If ( SIZ_WinW < 1024 )
SIZ_WinNewW = 1024
Else
If ( SIZ_WinW < 1152 )
SIZ_WinNewW = 1152
Else
If ( SIZ_WinW < 1280 )
SIZ_WinNewW = 1280
Else
If ( SIZ_WinW < 1400 )
SIZ_WinNewW = 1400
Else
If ( SIZ_WinW < 1600 )
SIZ_WinNewW = 1600
Else
SIZ_WinNewW = 1920
Else
If ( SIZ_WinW <= 320 )
SIZ_WinNewW = 160
Else
If ( SIZ_WinW <= 640 )
SIZ_WinNewW = 320
Else
If ( SIZ_WinW <= 800 )
SIZ_WinNewW = 640
Else
If ( SIZ_WinW <= 1024 )
SIZ_WinNewW = 800
Else
If ( SIZ_WinW <= 1152 )
SIZ_WinNewW = 1024
Else
If ( SIZ_WinW <= 1280 )
SIZ_WinNewW = 1152
Else
If ( SIZ_WinW <= 1400 )
SIZ_WinNewW = 1280
Else
If ( SIZ_WinW <= 1600 )
SIZ_WinNewW = 1400
Else
If ( SIZ_WinW <= 1920 )
SIZ_WinNewW = 1600
Else
SIZ_WinNewW = 1920
If ( SIZ_WinNewW > A_ScreenWidth )
SIZ_WinNewW := A_ScreenWidth
SIZ_WinNewH := 3 * SIZ_WinNewW / 4
If ( SIZ_WinNewW = 1280 )
SIZ_WinNewH := 1024
IfInString, A_ThisHotkey, #
{
SIZ_WinNewX := SIZ_WinX + (SIZ_WinW - SIZ_WinNewW) / 2
SIZ_WinNewY := SIZ_WinY + (SIZ_WinH - SIZ_WinNewH) / 2
}
Else
{
SIZ_WinNewX := SIZ_WinX
SIZ_WinNewY := SIZ_WinY
}
Transform, SIZ_WinNewX, Round, %SIZ_WinNewX%
Transform, SIZ_WinNewY, Round, %SIZ_WinNewY%
Transform, SIZ_WinNewW, Round, %SIZ_WinNewW%
Transform, SIZ_WinNewH, Round, %SIZ_WinNewH%
WinMove, ahk_id %SIZ_WinID%, , SIZ_WinNewX, SIZ_WinNewY, SIZ_WinNewW, SIZ_WinNewH
If ( SYS_ToolTipFeedback )
{
WinGetPos, SIZ_ToolTipWinX, SIZ_ToolTipWinY, SIZ_ToolTipWinW, SIZ_ToolTipWinH, ahk_id %SIZ_WinID%
SYS_ToolTipText = Window Size: (X:%SIZ_ToolTipWinX%, Y:%SIZ_ToolTipWinY%, W:%SIZ_ToolTipWinW%, H:%SIZ_ToolTipWinH%)
Gosub, SYS_ToolTipFeedbackShow
}
}
}
Return
; [XWN] provides X Window like focus switching (focus follows mouse)
/**
* Provided a 'X Window' like focus switching by mouse cursor movement. After
* activation of this feature (by using the responsible entry in the tray icon
* menu) the focus will follow the mouse cursor with a delayed focus change
* (after movement end) of 500 milliseconds (half a second). This feature is
* disabled per default to avoid any confusion due to the new user-interface-flow.
*/
XWN_FocusHandler:
CoordMode, Mouse, Screen
MouseGetPos, XWN_MouseX, XWN_MouseY, XWN_WinID
If ( !XWN_WinID )
Return
If ( (XWN_MouseX != XWN_MouseOldX) or (XWN_MouseY != XWN_MouseOldY) )
{
IfWinNotActive, ahk_id %XWN_WinID%
XWN_FocusRequest = 1
Else
XWN_FocusRequest = 0
XWN_MouseOldX := XWN_MouseX
XWN_MouseOldY := XWN_MouseY
XWN_MouseMovedTickCount := A_TickCount
}
Else
If ( XWN_FocusRequest and (A_TickCount - XWN_MouseMovedTickCount > 500) )
{
WinGetClass, XWN_WinClass, ahk_id %XWN_WinID%
If ( XWN_WinClass = "Progman" )
Return
; checks wheter the selected window is a popup menu
; (WS_POPUP) and !(WS_DLGFRAME | WS_SYSMENU | WS_THICKFRAME)
WinGet, XWN_WinStyle, Style, ahk_id %XWN_WinID%
If ( (XWN_WinStyle & 0x80000000) and !(XWN_WinStyle & 0x4C0000) )
Return
IfWinNotActive, ahk_id %XWN_WinID%
WinActivate, ahk_id %XWN_WinID%
XWN_FocusRequest = 0
}
Return
; [GRP] groups windows for quick task switching
/**
* Activates the next window in a process window group that was defined
* gradually before with the given CTRL modifier. This feature causes the first
* window of the responsible group to be activated. Using it a second time will
* activate the next window in the series and so on. By using process window
* groups you can organize and access your process windows in semantic groups
* quickly.
*/
^#F1::
^#F2::
^#F3::
^#F4::
^#F5::
^#F6::
^#F7::
^#F8::
^#F9::
^#F10::
^#F11::
^#F12::
^#F13::
^#F14::
^#F15::
^#F16::
^#F17::
^#F18::
^#F19::
^#F20::
^#F21::
^#F22::
^#F23::
^#F24::
IfWinActive, A
{
WinGet, GRP_WinID, ID
If ( !GRP_WinID )
Return
WinGetClass, GRP_WinClass, ahk_id %GRP_WinID%
If ( GRP_WinClass = "Progman" )
Return
WinGet, GRP_WinPID, PID
If ( !GRP_WinPID )
Return
StringMid, GRP_GroupNumber, A_ThisHotkey, 3, 3
GroupAdd, Group%GRP_GroupNumber%, ahk_PID %GRP_WinPID%
SYS_ToolTipText = Active window was added to group %GRP_GroupNumber%.
Gosub, SYS_ToolTipFeedbackShow
}
Return
#F1::
#F2::
#F3::
#F4::
#F5::
#F6::
#F7::
#F8::
#F9::
#F10::
#F11::
#F12::
#F13::
#F14::
#F15::
#F16::
#F17::
#F18::
#F19::
#F20::
#F21::
#F22::
#F23::
#F24::
StringMid, GRP_GroupNumber, A_ThisHotkey, 2, 3
GroupActivate, Group%GRP_GroupNumber%
SYS_ToolTipText = Activated next window in group %GRP_GroupNumber%.
Gosub, SYS_ToolTipFeedbackShow
Return
!#F1::
!#F2::
!#F3::
!#F4::
!#F5::
!#F6::
!#F7::
!#F8::
!#F9::
!#F10::
!#F11::
!#F12::
!#F13::
!#F14::
!#F15::
!#F16::
!#F17::
!#F18::
!#F19::
!#F20::
!#F21::
!#F22::
!#F23::
!#F24::
StringMid, GRP_GroupNumber, A_ThisHotkey, 3, 3
GroupClose, Group%GRP_GroupNumber%, A
SYS_ToolTipText = Closed all windows in group %GRP_GroupNumber%.
Gosub, SYS_ToolTipFeedbackShow
Return
; [MIR] toggles the visibility of miranda buddy list
/**
* Toggles the visibility of the Miranda buddy list (if installed). Currently
* Miranda does not provide a hotkey to activate the buddy list if the window
* is still visible. Instead the opened (but not activated) buddy list will be
* minimized. This is not expected so this NiftyWindows feature provides the
* needed service asked by so many people.
*/
^+b::
IfExist, %MIR_MirandaFullPath%
{
SetTitleMatchMode, 3
DetectHiddenWindows, On
MIR_MirandaStart = 0
IfWinNotExist, Miranda IM
{
Run, %MIR_MirandaFullPath%, %MIR_MirandaDir%
WinWait, Miranda IM
MIR_MirandaStart=1
Sleep, 500
}
DetectHiddenWindows, Off
IfWinActive, Miranda IM
{
If ( !MIR_MirandaStart )
WinHide
}
Else
IfWinExist, Miranda IM
WinActivate
Else
{
DetectHiddenWindows, On
IfWinExist, Miranda IM
{
WinShow
WinActivate
}
}
}
Else
Send, ^+b
Return
; [MIR] toggles the visibility of last used miranda message container
/**
* Toggles the visibility of the last used Miranda message container
* (if installed). Currently Miranda does not provide a hotkey to activate the
* last used message container if there is no unread message waiting for your
* attention. So this hotkey will make a container visible (if it is minimized)
* and activate it. If there is no existing message container, this hotkey will
* do nothing.
*/
~^+u::
IfExist, %MIR_MirandaFullPath%
{
Sleep, 500
SetTitleMatchMode, 3
IfWinExist, ahk_class #32770
{
WinGetTitle, MIR_Title
IfNotInString MIR_Title, Mail
IfWinNotActive
WinActivate
}
}
Else
Send, ^+u
Return
; [TRY] handles the tray icon/menu
TRY_TrayInit:
Menu, TRAY, NoStandard
Menu, TRAY, Tip, %SYS_ScriptInfo%
If ( !A_IsCompiled )
{
Menu, AutoHotkey, Standard
Menu, TRAY, Add, AutoHotkey, :AutoHotkey
Menu, TRAY, Add
}
Menu, TRAY, Add, Help, TRY_TrayEvent
Menu, TRAY, Default, Help
Menu, TRAY, Add
Menu, TRAY, Add, About, TRY_TrayEvent
Menu, TRAY, Add
Menu, TRAY, Add, Mail Author, TRY_TrayEvent
Menu, TRAY, Add, View License, TRY_TrayEvent
Menu, TRAY, Add, Visit Website, TRY_TrayEvent
Menu, TRAY, Add, Check For Update, TRY_TrayEvent
Menu, TRAY, Add
Menu, MouseHooks, Add, Left Mouse Button, TRY_TrayEvent
Menu, MouseHooks, Add, Middle Mouse Button, TRY_TrayEvent
Menu, MouseHooks, Add, Right Mouse Button, TRY_TrayEvent
Menu, MouseHooks, Add, Fourth Mouse Button, TRY_TrayEvent
Menu, MouseHooks, Add, Fifth Mouse Button, TRY_TrayEvent
Menu, TRAY, Add, Mouse Hooks, :MouseHooks
Menu, TRAY, Add, ToolTip Feedback, TRY_TrayEvent
Menu, TRAY, Add, Auto Suspend, TRY_TrayEvent
Menu, TRAY, Add, Focus Follows Mouse, TRY_TrayEvent
Menu, TRAY, Add, Suspend All Hooks, TRY_TrayEvent
Menu, TRAY, Add, Revert Visual Effects, TRY_TrayEvent
Menu, TRAY, Add, Hide Tray Icon, TRY_TrayEvent
Menu, TRAY, Add
Menu, TRAY, Add, Exit, TRY_TrayEvent
Gosub, TRY_TrayUpdate
If ( A_IconHidden )
Menu, TRAY, Icon
Return
TRY_TrayUpdate:
If ( CFG_LeftMouseButtonHook )
Menu, MouseHooks, Check, Left Mouse Button
Else
Menu, MouseHooks, UnCheck, Left Mouse Button
If ( CFG_MiddleMouseButtonHook )
Menu, MouseHooks, Check, Middle Mouse Button
Else
Menu, MouseHooks, UnCheck, Middle Mouse Button
If ( CFG_RightMouseButtonHook )
Menu, MouseHooks, Check, Right Mouse Button
Else
Menu, MouseHooks, UnCheck, Right Mouse Button
If ( CFG_FourthMouseButtonHook )
Menu, MouseHooks, Check, Fourth Mouse Button
Else
Menu, MouseHooks, UnCheck, Fourth Mouse Button
If ( CFG_FifthMouseButtonHook )
Menu, MouseHooks, Check, Fifth Mouse Button
Else
Menu, MouseHooks, UnCheck, Fifth Mouse Button
If ( SYS_ToolTipFeedback )
Menu, TRAY, Check, ToolTip Feedback
Else
Menu, TRAY, UnCheck, ToolTip Feedback
If ( SUS_AutoSuspend )
Menu, TRAY, Check, Auto Suspend
Else
Menu, TRAY, UnCheck, Auto Suspend
If ( XWN_FocusFollowsMouse )
Menu, TRAY, Check, Focus Follows Mouse
Else
Menu, TRAY, UnCheck, Focus Follows Mouse
If ( A_IsSuspended )
Menu, TRAY, Check, Suspend All Hooks
Else
Menu, TRAY, UnCheck, Suspend All Hooks
Return
TRY_TrayEvent:
If ( !TRY_TrayEvent )
TRY_TrayEvent = %A_ThisMenuItem%
If ( TRY_TrayEvent = "Help" )
IfExist, %A_ScriptDir%\readme.txt
Run, "%A_ScriptDir%\readme.txt"
Else
{
SYS_TrayTipText = File couldn't be accessed:`n%A_ScriptDir%\readme.txt
SYS_TrayTipOptions = 3
Gosub, SYS_TrayTipShow
}
If ( TRY_TrayEvent = "About" )
{
SYS_TrayTipText = Copyright (c) 2004-2005 by Enovatic-Solutions.`nAll rights reserved. Use is subject to license terms.`n`nCompany:`tEnovatic-Solutions (IT Service Provider)`nAuthor:`t`tOliver Pfeiffer`, Bremen (GERMANY)`nEmail:`t`tniftywindows@enovatic.org
Gosub, SYS_TrayTipShow
}
If ( TRY_TrayEvent = "Mail Author" )
Run, mailto:niftywindows@enovatic.org?subject=%SYS_ScriptInfo% (build %SYS_ScriptBuild%)
If ( TRY_TrayEvent = "View License" )
IfExist, %A_ScriptDir%\license.txt
Run, "%A_ScriptDir%\license.txt"
Else
{
SYS_TrayTipText = File couldn't be accessed:`n%A_ScriptDir%\license.txt
SYS_TrayTipOptions = 3
Gosub, SYS_TrayTipShow
}
If ( TRY_TrayEvent = "Visit Website" )
Run, http://www.enovatic.org/products/niftywindows/
If ( TRY_TrayEvent = "Check For Update" )
Gosub, UPD_CheckForUpdate
If ( TRY_TrayEvent = "ToolTip Feedback" )
SYS_ToolTipFeedback := !SYS_ToolTipFeedback
If ( TRY_TrayEvent = "Auto Suspend" )
{
SUS_AutoSuspend := !SUS_AutoSuspend
Gosub, CFG_ApplySettings
}
If ( TRY_TrayEvent = "Focus Follows Mouse" )
{
XWN_FocusFollowsMouse := !XWN_FocusFollowsMouse
Gosub, CFG_ApplySettings
}
If ( TRY_TrayEvent = "Suspend All Hooks" )
Gosub, SUS_SuspendToggle
If ( TRY_TrayEvent = "Revert Visual Effects" )
Gosub, SYS_RevertVisualEffects
If ( TRY_TrayEvent = "Hide Tray Icon" )
{
SYS_TrayTipText = Tray icon will be hidden now.`nPress WIN+X to show it again.
SYS_TrayTipOptions = 2
SYS_TrayTipSeconds = 5
Gosub, SYS_TrayTipShow
SetTimer, TRY_TrayHide, 5000
}
If ( TRY_TrayEvent = "Exit" )
ExitApp
If ( TRY_TrayEvent = "Left Mouse Button" )
{
CFG_LeftMouseButtonHook := !CFG_LeftMouseButtonHook
Gosub, CFG_ApplySettings
}
If ( TRY_TrayEvent = "Middle Mouse Button" )
{
CFG_MiddleMouseButtonHook := !CFG_MiddleMouseButtonHook
Gosub, CFG_ApplySettings
}
If ( TRY_TrayEvent = "Right Mouse Button" )
{
CFG_RightMouseButtonHook := !CFG_RightMouseButtonHook
Gosub, CFG_ApplySettings
}
If ( TRY_TrayEvent = "Fourth Mouse Button" )
{
CFG_FourthMouseButtonHook := !CFG_FourthMouseButtonHook
Gosub, CFG_ApplySettings
}
If ( TRY_TrayEvent = "Fifth Mouse Button" )
{
CFG_FifthMouseButtonHook := !CFG_FifthMouseButtonHook
Gosub, CFG_ApplySettings
}
Gosub, TRY_TrayUpdate
TRY_TrayEvent =
Return
TRY_TrayHide:
SetTimer, TRY_TrayHide, Off
Menu, TRAY, NoIcon
Return
; [EDT] edits this script in notepad
^#!F9::
If ( A_IsCompiled )
Return
Gosub, SUS_SuspendSaveState
Suspend, On
MsgBox, 4129, Edit Handler - %SYS_ScriptInfo%, You pressed the hotkey for editing this script:`n`n%A_ScriptFullPath%`n`nDo you really want to edit?
Gosub, SUS_SuspendRestoreState
IfMsgBox, OK
Run, notepad.exe %A_ScriptFullPath%
Return
; [REL] reloads this script on change
REL_ScriptReload:
If ( A_IsCompiled )
Return
FileGetAttrib, REL_Attribs, %A_ScriptFullPath%
IfInString, REL_Attribs, A
{
FileSetAttrib, -A, %A_ScriptFullPath%
If ( REL_InitDone )
{
Gosub, SUS_SuspendSaveState
Suspend, On
MsgBox, 4145, Update Handler - %SYS_ScriptInfo%, The following script has changed:`n`n%A_ScriptFullPath%`n`nReload and activate this script?
Gosub, SUS_SuspendRestoreState
IfMsgBox, OK
Reload
}
}
REL_InitDone = 1
Return
; [EXT] exits this script
#x::
If ( A_IconHidden )
{
Menu, TRAY, Icon
SYS_TrayTipText = Tray icon is shown now.`nPress WIN+X again to exit NiftyWindows.
SYS_TrayTipSeconds = 5
Gosub, SYS_TrayTipShow
Return
}
If ( A_IsCompiled )
{
SYS_TrayTipText = NiftyWindows will exit now.`nYou can find it here (to start it again):`n%A_ScriptFullPath%
SYS_TrayTipOptions = 2
SYS_TrayTipSeconds = 5
Gosub, SYS_TrayTipShow
Suspend, On
Sleep, 5000
ExitApp
}
Gosub, SUS_SuspendSaveState
Suspend, On
MsgBox, 4145, Exit Handler - %SYS_ScriptInfo%, You pressed the hotkey for exiting this script:`n`n%A_ScriptFullPath%`n`nDo you really want to exit?
Gosub, SUS_SuspendRestoreState
IfMsgBox, OK
ExitApp
Return
; [CFG] handles the persistent configuration
CFG_LoadSettings:
CFG_IniFile = %A_ScriptDir%\%SYS_ScriptNameNoExt%.ini
IniRead, SUS_AutoSuspend, %CFG_IniFile%, Main, AutoSuspend, 1
IniRead, XWN_FocusFollowsMouse, %CFG_IniFile%, WindowHandling, FocusFollowsMouse, 0
IniRead, SYS_ToolTipFeedback, %CFG_IniFile%, Visual, ToolTipFeedback, 1
IniRead, UPD_LastUpdateCheck, %CFG_IniFile%, UpdateCheck, LastUpdateCheck, %A_MM%
IniRead, CFG_LeftMouseButtonHook, %CFG_IniFile%, MouseHooks, LeftMouseButton, 1
IniRead, CFG_MiddleMouseButtonHook, %CFG_IniFile%, MouseHooks, MiddleMouseButton, 1
IniRead, CFG_RightMouseButtonHook, %CFG_IniFile%, MouseHooks, RightMouseButton, 1
IniRead, CFG_FourthMouseButtonHook, %CFG_IniFile%, MouseHooks, FourthMouseButton, 1
IniRead, CFG_FifthMouseButtonHook, %CFG_IniFile%, MouseHooks, FifthMouseButton, 1
Return
CFG_SaveSettings:
CFG_IniFile = %A_ScriptDir%\%SYS_ScriptNameNoExt%.ini
IniWrite, %SUS_AutoSuspend%, %CFG_IniFile%, Main, AutoSuspend
IniWrite, %XWN_FocusFollowsMouse%, %CFG_IniFile%, WindowHandling, FocusFollowsMouse
IniWrite, %SYS_ToolTipFeedback%, %CFG_IniFile%, Visual, ToolTipFeedback
IniWrite, %UPD_LastUpdateCheck%, %CFG_IniFile%, UpdateCheck, LastUpdateCheck
IniWrite, %CFG_LeftMouseButtonHook%, %CFG_IniFile%, MouseHooks, LeftMouseButton
IniWrite, %CFG_MiddleMouseButtonHook%, %CFG_IniFile%, MouseHooks, MiddleMouseButton
IniWrite, %CFG_RightMouseButtonHook%, %CFG_IniFile%, MouseHooks, RightMouseButton
IniWrite, %CFG_FourthMouseButtonHook%, %CFG_IniFile%, MouseHooks, FourthMouseButton
IniWrite, %CFG_FifthMouseButtonHook%, %CFG_IniFile%, MouseHooks, FifthMouseButton
Return
CFG_ApplySettings:
If ( SUS_AutoSuspend )
SetTimer, SUS_SuspendHandler, 1000
Else
SetTimer, SUS_SuspendHandler, Off
If ( XWN_FocusFollowsMouse )
SetTimer, XWN_FocusHandler, 100
Else
SetTimer, XWN_FocusHandler, Off
If ( CFG_LeftMouseButtonHook )
CFG_LeftMouseButtonHookStr = On
Else
CFG_LeftMouseButtonHookStr = Off
If ( CFG_MiddleMouseButtonHook )
CFG_MiddleMouseButtonHookStr = On
Else
CFG_MiddleMouseButtonHookStr = Off
If ( CFG_RightMouseButtonHook )
CFG_RightMouseButtonHookStr = On
Else
CFG_RightMouseButtonHookStr = Off
If ( CFG_FourthMouseButtonHook )
CFG_FourthMouseButtonHookStr = On
Else
CFG_FourthMouseButtonHookStr = Off
If ( CFG_FifthMouseButtonHook )
CFG_FifthMouseButtonHookStr = On
Else
CFG_FifthMouseButtonHookStr = Off
Hotkey, $LButton, %CFG_LeftMouseButtonHookStr%
Hotkey, $^LButton, %CFG_LeftMouseButtonHookStr%
Hotkey, #LButton, %CFG_LeftMouseButtonHookStr%
Hotkey, #^LButton, %CFG_LeftMouseButtonHookStr%
Hotkey, #MButton, %CFG_MiddleMouseButtonHookStr%
Hotkey, #^MButton, %CFG_MiddleMouseButtonHookStr%
Hotkey, $MButton, %CFG_MiddleMouseButtonHookStr%
Hotkey, $^MButton, %CFG_MiddleMouseButtonHookStr%
Hotkey, $RButton, %CFG_RightMouseButtonHookStr%
Hotkey, $+RButton, %CFG_RightMouseButtonHookStr%
Hotkey, $+!RButton, %CFG_RightMouseButtonHookStr%
Hotkey, $+^RButton, %CFG_RightMouseButtonHookStr%
Hotkey, $+#RButton, %CFG_RightMouseButtonHookStr%
Hotkey, $+!^RButton, %CFG_RightMouseButtonHookStr%
Hotkey, $+!#RButton, %CFG_RightMouseButtonHookStr%
Hotkey, $+^#RButton, %CFG_RightMouseButtonHookStr%
Hotkey, $+!^#RButton, %CFG_RightMouseButtonHookStr%
Hotkey, $!RButton, %CFG_RightMouseButtonHookStr%
Hotkey, $!^RButton, %CFG_RightMouseButtonHookStr%
Hotkey, $!#RButton, %CFG_RightMouseButtonHookStr%
Hotkey, $!^#RButton, %CFG_RightMouseButtonHookStr%
Hotkey, $^RButton, %CFG_RightMouseButtonHookStr%
Hotkey, $^#RButton, %CFG_RightMouseButtonHookStr%
Hotkey, $#RButton, %CFG_RightMouseButtonHookStr%
Hotkey, $XButton1, %CFG_FourthMouseButtonHookStr%
Hotkey, $^XButton1, %CFG_FourthMouseButtonHookStr%
Hotkey, $XButton2, %CFG_FifthMouseButtonHookStr%
Hotkey, $^XButton2, %CFG_FifthMouseButtonHookStr%
Return
; [UPD] checks for a new build
UPD_CheckForUpdate:
UPD_CheckSuccess =
Random, UPD_Random
If ( TEMP )
UPD_BuildFile = %TEMP%\%SYS_ScriptNameNoExt%.%UPD_Random%.tmp
Else
UPD_BuildFile = %SYS_ScriptDir%\%SYS_ScriptNameNoExt%.%UPD_Random%.tmp
Gosub, SUS_SuspendSaveState
Suspend, On
URLDownloadToFile, http://www.enovatic.org/products/niftywindows/files/build.txt?random=%UPD_Random%, %UPD_BuildFile%
Gosub, SUS_SuspendRestoreState
If ( !ErrorLevel )
{
FileReadLine, UPD_Build, %UPD_BuildFile%, 1
If ( !ErrorLevel )
If UPD_Build is digit
{
UPD_CheckSuccess = 1
UPD_LastUpdateCheck = %A_MM%
If ( UPD_Build > SYS_ScriptBuild )
{
SYS_TrayTipText = There is a new version available. Please check website.
SYS_TrayTipOptions = 1
Run, http://www.enovatic.org/products/niftywindows/
}
Else
SYS_TrayTipText = There is no new version available.
}
Else
SYS_TrayTipText = wrong build pattern in downloaded build file
Else
SYS_TrayTipText = downloaded build file couldn't be read
}
Else
SYS_TrayTipText = build file couldn't be downloaded
FileDelete, %UPD_BuildFile%
If ( !UPD_CheckSuccess )
{
SYS_TrayTipText = Check for update failed:`n%SYS_TrayTipText%
SYS_TrayTipOptions = 3
}
Gosub, SYS_TrayTipShow
Return
UPD_AutoCheckForUpdate:
If ( UPD_LastUpdateCheck != A_MM )
{
Gosub, SUS_SuspendSaveState
Suspend, On
MsgBox, 4132, Update Handler - %SYS_ScriptInfo%, You haven't checked for updates for a long period of time (at least one month).`n`nDo you want NiftyWindows to check for a new version now (highly recommended)?
Gosub, SUS_SuspendRestoreState
IfMsgBox, Yes
Gosub, UPD_CheckForUpdate
Else
UPD_LastUpdateCheck = %A_MM%
}
Return
^#!b::
If ( !A_IsCompiled )
{
UPD_VersionFile = %SYS_ScriptDir%\version.txt
IfExist, %UPD_VersionFile%
{
FileDelete, %UPD_VersionFile%
If ( ErrorLevel )
Return
}
FileAppend, %SYS_ScriptVersion%, %UPD_VersionFile%
If ( ErrorLevel )
Return
UPD_BuildFile = %SYS_ScriptDir%\build.txt
IfExist, %UPD_BuildFile%
{
FileDelete, %UPD_BuildFile%
If ( ErrorLevel )
Return
}
FileAppend, %A_NowUTC%, %UPD_BuildFile%
If ( ErrorLevel )
Return
SYS_TrayTipText = Version and build files were written successfully:`n%UPD_VersionFile%`n%UPD_BuildFile%
SYS_TrayTipOptions = 2
SYS_TrayTipSeconds = 5
Gosub, SYS_TrayTipShow
}
Return
A modification of the NiftyWindows AutoHotkey script, this snippet attempts to solve the following issues that I have been experiencing with the original script: * Middle click sends double click. This causes an issue for me as I use middle clicks to close: * Tabs * Applications using the title bar (this snippet adds this functionality) * Applications using the task bar (this snippet allows middle clicks through to non-title bar areas if right button is not also pressed)
William_Wilson/Multi-Column JList ( Java)
import java.io.*;
import java.awt.*;
import java.util.*;
import java.text.*;
import javax.swing.*;
import java.awt.event.*;
import javax.swing.event.*;
public class MultiColumn{
JFrame jf;
JScrollPane scroll;
JList list;
String[][] columnData;
public MultiColumn(){
//create the frame and JList JPanel
jf = new aFrame();
//create element List array
addElements();
//set list for JList
list.setListData(columnData);
//create Renderer and dislpay
list.setCellRenderer(new MyCellRenderer());
}
public void addElements(){
//first number is number of rows, second is number of columns
columnData = new String[4][3];
//static setting of String[][]
columnData[0][0] = "William";
columnData[0][1] = "A";
columnData[0][2] = "Wilson";
//dynamic setting of String[][]
for(int i=1;i<4;i++){
columnData[i][0] = "William";
columnData[i][1] = String.valueOf(i*13);
Calendar c = new GregorianCalendar();
columnData[i][2] = ((Date)c.getTime()).toString();
}
}
public class aFrame extends JFrame{
public aFrame(){
super("Multi-Column JList Example");
getContentPane().add(new PanelBuilder());
// display rules
setResizable(true);
setLocation(250,50);
setBackground(Color.lightGray);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(650, 400);
setVisible(true);
}
private class PanelBuilder extends JPanel{
public PanelBuilder(){
GridBagLayout layout = new GridBagLayout();
GridBagConstraints layoutConstraints = new GridBagConstraints();
setLayout(layout);
scroll = new JScrollPane();
list = new JList();
layoutConstraints.gridx = 0; layoutConstraints.gridy = 0;
layoutConstraints.gridwidth = 1; layoutConstraints.gridheight = 1;
layoutConstraints.fill = GridBagConstraints.BOTH;
layoutConstraints.insets = new Insets(1, 1, 1, 1);
layoutConstraints.anchor = GridBagConstraints.CENTER;
layoutConstraints.weightx = 1.0; layoutConstraints.weighty = 1.0;
scroll = new JScrollPane(list,JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
JScrollPane. HORIZONTAL_SCROLLBAR_NEVER);
layout.setConstraints(scroll, layoutConstraints);
add(scroll);
}
}
}
static class MyCellRenderer extends JPanel implements ListCellRenderer{
JLabel left, middle, right;
MyCellRenderer() {
setLayout(new GridLayout(1, 3));
left = new JLabel();
middle = new JLabel();
right = new JLabel();
left.setOpaque(true);
middle.setOpaque(true);
right.setOpaque(true);
add(left);
add(middle);
add(right);
}
public Component getListCellRendererComponent(JList list,Object value,int index,boolean isSelected,boolean cellHasFocus){
String leftData = ((String[])value)[0];
String middleData = ((String[])value)[1];
String rightData = ((String[])value)[2];
left.setText(leftData);
middle.setText(middleData);
right.setText(rightData);
if(isSelected){
left.setBackground(list.getSelectionBackground());
left.setForeground(list.getSelectionForeground());
middle.setBackground(list.getSelectionBackground());
middle.setForeground(list.getSelectionForeground());
right.setBackground(list.getSelectionBackground());
right.setForeground(list.getSelectionForeground());
}
else{
left.setBackground(list.getBackground());
left.setForeground(list.getForeground());
middle.setBackground(list.getBackground());
middle.setForeground(list.getForeground());
right.setBackground(list.getBackground());
right.setForeground(list.getForeground());
}
setEnabled(list.isEnabled());
setFont(list.getFont());
return this;
}
}
public static void main(String args[]){
MultiColumn jf = new MultiColumn();
}
}
/*I have found this useful on countless occassions, enjoy*/
/*William_Wilson. §*/
Auto Aligning columns of a JList which act as a single row
kiran8049/Override servicePreaction using hook ( Java)
package com.ssdg.portal.events;
import com.liferay.portal.LayoutPermissionException;
import com.liferay.portal.NoSuchGroupException;
import com.liferay.portal.NoSuchLayoutException;
import com.liferay.portal.NoSuchUserException;
import com.liferay.portal.kernel.dao.orm.QueryUtil;
import com.liferay.portal.kernel.events.Action;
import com.liferay.portal.kernel.events.ActionException;
import com.liferay.portal.kernel.exception.PortalException;
import com.liferay.portal.kernel.exception.SystemException;
import com.liferay.portal.kernel.language.LanguageUtil;
import com.liferay.portal.kernel.lar.PortletDataHandlerKeys;
import com.liferay.portal.kernel.log.Log;
import com.liferay.portal.kernel.log.LogFactoryUtil;
import com.liferay.portal.kernel.portlet.LiferayPortletURL;
import com.liferay.portal.kernel.portlet.LiferayWindowState;
import com.liferay.portal.kernel.servlet.BrowserSnifferUtil;
import com.liferay.portal.kernel.servlet.HttpHeaders;
import com.liferay.portal.kernel.servlet.SessionErrors;
import com.liferay.portal.kernel.util.FriendlyURLNormalizerUtil;
import com.liferay.portal.kernel.util.GetterUtil;
import com.liferay.portal.kernel.util.HttpUtil;
import com.liferay.portal.kernel.util.LocaleUtil;
import com.liferay.portal.kernel.util.ParamUtil;
import com.liferay.portal.kernel.util.PropsKeys;
import com.liferay.portal.kernel.util.SessionParamUtil;
import com.liferay.portal.kernel.util.StringBundler;
import com.liferay.portal.kernel.util.StringPool;
import com.liferay.portal.kernel.util.StringUtil;
import com.liferay.portal.kernel.util.UnicodeProperties;
import com.liferay.portal.kernel.util.Validator;
import com.liferay.portal.model.ColorScheme;
import com.liferay.portal.model.Company;
import com.liferay.portal.model.Group;
import com.liferay.portal.model.GroupConstants;
import com.liferay.portal.model.Image;
import com.liferay.portal.model.Layout;
import com.liferay.portal.model.LayoutConstants;
import com.liferay.portal.model.LayoutSet;
import com.liferay.portal.model.LayoutTypePortlet;
import com.liferay.portal.model.LayoutTypePortletConstants;
import com.liferay.portal.model.Portlet;
import com.liferay.portal.model.RoleConstants;
import com.liferay.portal.model.Theme;
import com.liferay.portal.model.User;
import com.liferay.portal.model.impl.ColorSchemeImpl;
import com.liferay.portal.model.impl.VirtualLayout;
import com.liferay.portal.security.auth.PrincipalException;
import com.liferay.portal.security.permission.ActionKeys;
import com.liferay.portal.security.permission.PermissionChecker;
import com.liferay.portal.security.permission.PermissionCheckerFactoryUtil;
import com.liferay.portal.security.permission.PermissionThreadLocal;
import com.liferay.portal.service.GroupLocalServiceUtil;
import com.liferay.portal.service.ImageLocalServiceUtil;
import com.liferay.portal.service.LayoutLocalServiceUtil;
import com.liferay.portal.service.LayoutSetLocalServiceUtil;
import com.liferay.portal.service.PortletLocalServiceUtil;
import com.liferay.portal.service.RoleLocalServiceUtil;
import com.liferay.portal.service.ServiceContext;
import com.liferay.portal.service.ServiceContextFactory;
import com.liferay.portal.service.ServiceContextThreadLocal;
import com.liferay.portal.service.ThemeLocalServiceUtil;
import com.liferay.portal.service.UserLocalServiceUtil;
import com.liferay.portal.service.permission.GroupPermissionUtil;
import com.liferay.portal.service.permission.LayoutPermissionUtil;
import com.liferay.portal.service.permission.PortletPermissionUtil;
import com.liferay.portal.theme.ThemeDisplay;
import com.liferay.portal.theme.ThemeDisplayFactory;
import com.liferay.portal.util.CookieKeys;
import com.liferay.portal.util.LayoutClone;
import com.liferay.portal.util.LayoutCloneFactory;
import com.liferay.portal.util.PortalUtil;
import com.liferay.portal.util.PortletCategoryKeys;
import com.liferay.portal.util.PortletKeys;
import com.liferay.portal.util.PrefsPropsUtil;
import com.liferay.portal.util.PropsUtil;
import com.liferay.portal.util.PropsValues;
import com.liferay.portal.util.WebKeys;
import com.liferay.portal.webserver.WebServerServletTokenUtil;
import com.liferay.portlet.PortalPreferences;
import com.liferay.portlet.PortletPreferencesFactoryUtil;
import com.liferay.portlet.PortletURLImpl;
import com.liferay.portlet.asset.model.AssetEntry;
import com.liferay.portlet.asset.service.AssetEntryLocalServiceUtil;
import com.liferay.portlet.journal.NoSuchArticleException;
import com.liferay.portlet.journal.model.JournalArticle;
import com.liferay.portlet.journal.service.JournalArticleServiceUtil;
import com.liferay.portlet.sites.util.SitesUtil;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.TimeZone;
import javax.portlet.PortletMode;
import javax.portlet.PortletRequest;
import javax.portlet.PortletURL;
import javax.portlet.WindowState;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.commons.lang3.time.StopWatch;
import org.apache.struts.Globals;
public class ServicePreAction extends Action {
public ServicePreAction() {
initImportLARFiles();
}
public ThemeDisplay initThemeDisplay(
HttpServletRequest request, HttpServletResponse response)
throws Exception {
HttpSession session = request.getSession();
// Company
Company company = PortalUtil.getCompany(request);
long companyId = company.getCompanyId();
// CDN host
String cdnHost = PortalUtil.getCDNHost(request);
// Portal URL
String portalURL = PortalUtil.getPortalURL(request);
// Paths
String contextPath = PortalUtil.getPathContext();
String friendlyURLPrivateGroupPath =
PortalUtil.getPathFriendlyURLPrivateGroup();
String friendlyURLPrivateUserPath =
PortalUtil.getPathFriendlyURLPrivateUser();
String friendlyURLPublicPath = PortalUtil.getPathFriendlyURLPublic();
String imagePath = cdnHost.concat(PortalUtil.getPathImage());
String mainPath = PortalUtil.getPathMain();
String i18nPath = (String)request.getAttribute(WebKeys.I18N_PATH);
if (Validator.isNotNull(i18nPath)) {
if (Validator.isNotNull(contextPath)) {
String i18nContextPath = contextPath.concat(i18nPath);
friendlyURLPrivateGroupPath = StringUtil.replaceFirst(
friendlyURLPrivateGroupPath, contextPath, i18nContextPath);
friendlyURLPrivateUserPath = StringUtil.replaceFirst(
friendlyURLPrivateUserPath, contextPath, i18nContextPath);
friendlyURLPublicPath = StringUtil.replaceFirst(
friendlyURLPublicPath, contextPath, i18nContextPath);
mainPath = StringUtil.replaceFirst(
mainPath, contextPath, i18nContextPath);
}
else {
friendlyURLPrivateGroupPath = i18nPath.concat(
friendlyURLPrivateGroupPath);
friendlyURLPrivateUserPath = i18nPath.concat(
friendlyURLPrivateUserPath);
friendlyURLPublicPath = i18nPath.concat(friendlyURLPublicPath);
mainPath = i18nPath.concat(mainPath);
}
}
// Company logo
StringBundler sb = new StringBundler(5);
sb.append(imagePath);
sb.append("/company_logo?img_id=");
sb.append(company.getLogoId());
sb.append("&t=");
sb.append(WebServerServletTokenUtil.getToken(company.getLogoId()));
String companyLogo = sb.toString();
int companyLogoHeight = 0;
int companyLogoWidth = 0;
Image companyLogoImage = ImageLocalServiceUtil.getCompanyLogo(
company.getLogoId());
if (companyLogoImage != null) {
companyLogoHeight = companyLogoImage.getHeight();
companyLogoWidth = companyLogoImage.getWidth();
}
String realCompanyLogo = companyLogo;
int realCompanyLogoHeight = companyLogoHeight;
int realCompanyLogoWidth = companyLogoWidth;
// User
User user = null;
try {
user = PortalUtil.getUser(request);
}
catch (NoSuchUserException nsue) {
if (_log.isWarnEnabled()) {
_log.warn(nsue.getMessage());
}
long userId = PortalUtil.getUserId(request);
if (userId > 0) {
session.invalidate();
}
return null;
}
boolean signedIn = false;
if (user == null) {
user = company.getDefaultUser();
}
else if (!user.isDefaultUser()) {
signedIn = true;
}
if (PropsValues.BROWSER_CACHE_DISABLED ||
(PropsValues.BROWSER_CACHE_SIGNED_IN_DISABLED && signedIn)) {
response.setDateHeader(HttpHeaders.EXPIRES, 0);
response.setHeader(
HttpHeaders.CACHE_CONTROL,
HttpHeaders.CACHE_CONTROL_NO_CACHE_VALUE);
response.setHeader(
HttpHeaders.PRAGMA, HttpHeaders.PRAGMA_NO_CACHE_VALUE);
}
User realUser = user;
Long realUserId = (Long)session.getAttribute(WebKeys.USER_ID);
if (realUserId != null) {
if (user.getUserId() != realUserId.longValue()) {
realUser = UserLocalServiceUtil.getUserById(
realUserId.longValue());
}
}
String doAsUserId = ParamUtil.getString(request, "doAsUserId");
String doAsUserLanguageId = ParamUtil.getString(
request, "doAsUserLanguageId");
long doAsGroupId = ParamUtil.getLong(request, "doAsGroupId");
long refererPlid = ParamUtil.getLong(request, "refererPlid");
if (LayoutLocalServiceUtil.fetchLayout(refererPlid) == null) {
refererPlid = 0;
}
String controlPanelCategory = ParamUtil.getString(
request, "controlPanelCategory");
// Permission checker
PermissionChecker permissionChecker =
PermissionCheckerFactoryUtil.create(user, true);
PermissionThreadLocal.setPermissionChecker(permissionChecker);
// Locale
Locale locale = (Locale)session.getAttribute(Globals.LOCALE_KEY);
if (Validator.isNotNull(doAsUserLanguageId)) {
locale = LocaleUtil.fromLanguageId(doAsUserLanguageId);
}
String i18nLanguageId = (String)request.getAttribute(
WebKeys.I18N_LANGUAGE_ID);
if (Validator.isNotNull(i18nLanguageId)) {
locale = LocaleUtil.fromLanguageId(i18nLanguageId);
}
else if (locale == null) {
if (signedIn) {
locale = user.getLocale();
}
else {
// User previously set their preferred language
String languageId = CookieKeys.getCookie(
request, CookieKeys.GUEST_LANGUAGE_ID, false);
if (Validator.isNotNull(languageId)) {
locale = LocaleUtil.fromLanguageId(languageId);
}
// Get locale from the request
if ((locale == null) && PropsValues.LOCALE_DEFAULT_REQUEST) {
locale = request.getLocale();
}
// Get locale from the default user
if (locale == null) {
locale = user.getLocale();
}
if (Validator.isNull(locale.getCountry())) {
// Locales must contain a country code
locale = LanguageUtil.getLocale(locale.getLanguage());
}
if (!LanguageUtil.isAvailableLocale(locale)) {
locale = user.getLocale();
}
}
session.setAttribute(Globals.LOCALE_KEY, locale);
LanguageUtil.updateCookie(request, response, locale);
}
// Cookie support
try {
// LEP-4069
CookieKeys.validateSupportCookie(request);
}
catch (Exception e) {
CookieKeys.addSupportCookie(request, response);
}
// Time zone
TimeZone timeZone = user.getTimeZone();
if (timeZone == null) {
timeZone = company.getTimeZone();
}
// Layouts
if (signedIn) {
updateUserLayouts(user);
}
Layout layout = null;
List<Layout> layouts = null;
long plid = ParamUtil.getLong(request, "p_l_id");
if (plid > 0) {
layout = LayoutLocalServiceUtil.getLayout(plid);
long sourceGroupId = ParamUtil.getLong(request, "p_v_l_s_g_id");
if ((sourceGroupId > 0) && (sourceGroupId != layout.getGroupId())) {
Group sourceGroup = GroupLocalServiceUtil.getGroup(
sourceGroupId);
if (SitesUtil.isUserGroupLayoutSetViewable(
permissionChecker, layout.getGroup())) {
layout = new VirtualLayout(layout, sourceGroup);
}
else {
layout = null;
}
}
}
else {
long groupId = ParamUtil.getLong(request, "groupId");
boolean privateLayout = ParamUtil.getBoolean(
request, "privateLayout");
long layoutId = ParamUtil.getLong(request, "layoutId");
if ((groupId > 0) && (layoutId > 0)) {
layout = LayoutLocalServiceUtil.getLayout(
groupId, privateLayout, layoutId);
}
}
Boolean redirectToDefaultLayout = (Boolean)request.getAttribute(
WebKeys.REDIRECT_TO_DEFAULT_LAYOUT);
if (redirectToDefaultLayout == null) {
redirectToDefaultLayout = Boolean.FALSE;
}
if (layout != null) {
Group group = layout.getGroup();
if (!signedIn && PropsValues.AUTH_FORWARD_BY_REDIRECT) {
request.setAttribute(WebKeys.REQUESTED_LAYOUT, layout);
}
boolean isViewableGroup = LayoutPermissionUtil.contains(
permissionChecker, layout, controlPanelCategory, true,
ActionKeys.VIEW);
boolean isViewableStaging = GroupPermissionUtil.contains(
permissionChecker, group.getGroupId(),
ActionKeys.VIEW_STAGING);
if (isViewableStaging) {
layouts = LayoutLocalServiceUtil.getLayouts(
layout.getGroupId(), layout.isPrivateLayout(),
LayoutConstants.DEFAULT_PARENT_LAYOUT_ID);
}
else if (!isViewableGroup && group.isStagingGroup()) {
layout = null;
}
else if (!isLoginRequest(request) &&
(!isViewableGroup ||
(!redirectToDefaultLayout &&
!LayoutPermissionUtil.contains(
permissionChecker, layout, false,
ActionKeys.VIEW)))) {
if (user.isDefaultUser()) {
throw new PrincipalException("User is not authenticated");
}
sb = new StringBundler(6);
sb.append("User ");
sb.append(user.getUserId());
sb.append(" is not allowed to access the ");
sb.append(layout.isPrivateLayout() ? "private": "public");
sb.append(" pages of group ");
sb.append(layout.getGroupId());
if (_log.isWarnEnabled()) {
_log.warn(sb.toString());
}
throw new NoSuchLayoutException(sb.toString());
}
else if (group.isLayoutPrototype()) {
layouts = new ArrayList<Layout>();
}
else {
layouts = LayoutLocalServiceUtil.getLayouts(
layout.getGroupId(), layout.isPrivateLayout(),
LayoutConstants.DEFAULT_PARENT_LAYOUT_ID);
if (!group.isControlPanel()) {
doAsGroupId = 0;
}
}
}
List<Layout> unfilteredLayouts = layouts;
if (layout == null) {
Object[] defaultLayout = getDefaultLayout(request, user, signedIn);
layout = (Layout)defaultLayout[0];
layouts = (List<Layout>)defaultLayout[1];
request.setAttribute(WebKeys.LAYOUT_DEFAULT, Boolean.TRUE);
}
Object[] viewableLayouts = getViewableLayouts(
request, user, permissionChecker, layout, layouts);
String layoutSetLogo = null;
layout = (Layout)viewableLayouts[0];
layouts = (List<Layout>)viewableLayouts[1];
Group group = null;
if (layout != null) {
group = layout.getGroup();
if (!group.isControlPanel()) {
rememberVisitedGroupIds(request, group.getGroupId());
}
}
LayoutTypePortlet layoutTypePortlet = null;
layouts = mergeAdditionalLayouts(
request, user, permissionChecker, layout, layouts);
LayoutSet layoutSet = null;
boolean hasCustomizeLayoutPermission = false;
boolean hasUpdateLayoutPermission = false;
boolean customizedView = SessionParamUtil.getBoolean(
request, "customized_view", true);
if (layout != null) {
hasCustomizeLayoutPermission = LayoutPermissionUtil.contains(
permissionChecker, layout, ActionKeys.CUSTOMIZE);
hasUpdateLayoutPermission = LayoutPermissionUtil.contains(
permissionChecker, layout, ActionKeys.UPDATE);
layoutSet = layout.getLayoutSet();
if (company.isSiteLogo()) {
long logoId = 0;
if (layoutSet.isLogo()) {
logoId = layoutSet.getLogoId();
}
else {
LayoutSet siblingLayoutSet =
LayoutSetLocalServiceUtil.getLayoutSet(
layout.getGroupId(), !layout.isPrivateLayout());
if (siblingLayoutSet.isLogo()) {
logoId = siblingLayoutSet.getLogoId();
}
}
if (logoId > 0) {
sb = new StringBundler(5);
sb.append(imagePath);
sb.append("/layout_set_logo?img_id=");
sb.append(logoId);
sb.append("&t=");
sb.append(WebServerServletTokenUtil.getToken(logoId));
layoutSetLogo = sb.toString();
Image layoutSetLogoImage =
ImageLocalServiceUtil.getCompanyLogo(logoId);
companyLogo = layoutSetLogo;
companyLogoHeight = layoutSetLogoImage.getHeight();
companyLogoWidth = layoutSetLogoImage.getWidth();
}
}
plid = layout.getPlid();
// Updates to shared layouts are not reflected until the next time
// the user logs in because group layouts are cached in the session
layout = (Layout)layout.clone();
layoutTypePortlet = (LayoutTypePortlet)layout.getLayoutType();
boolean customizable = layoutTypePortlet.isCustomizable();
if (!customizable ||
(group.isLayoutPrototype() || group.isLayoutSetPrototype())) {
customizedView = false;
}
layoutTypePortlet.setCustomizedView(customizedView);
layoutTypePortlet.setUpdatePermission(hasUpdateLayoutPermission);
if (signedIn && customizable && customizedView &&
hasCustomizeLayoutPermission) {
PortalPreferences portalPreferences =
PortletPreferencesFactoryUtil.getPortalPreferences(
companyId, user.getUserId(), true);
layoutTypePortlet.setPortalPreferences(portalPreferences);
}
LayoutClone layoutClone = LayoutCloneFactory.getInstance();
if (layoutClone != null) {
String typeSettings = layoutClone.get(request, plid);
if (typeSettings != null) {
UnicodeProperties typeSettingsProperties =
new UnicodeProperties(true);
typeSettingsProperties.load(typeSettings);
String stateMax = typeSettingsProperties.getProperty(
LayoutTypePortletConstants.STATE_MAX);
String stateMin = typeSettingsProperties.getProperty(
LayoutTypePortletConstants.STATE_MIN);
String modeAbout = typeSettingsProperties.getProperty(
LayoutTypePortletConstants.MODE_ABOUT);
String modeConfig = typeSettingsProperties.getProperty(
LayoutTypePortletConstants.MODE_CONFIG);
String modeEdit = typeSettingsProperties.getProperty(
LayoutTypePortletConstants.MODE_EDIT);
String modeEditDefaults =
typeSettingsProperties.getProperty(
LayoutTypePortletConstants.MODE_EDIT_DEFAULTS);
String modeEditGuest = typeSettingsProperties.getProperty(
LayoutTypePortletConstants.MODE_EDIT_GUEST);
String modeHelp = typeSettingsProperties.getProperty(
LayoutTypePortletConstants.MODE_HELP);
String modePreview = typeSettingsProperties.getProperty(
LayoutTypePortletConstants.MODE_PREVIEW);
String modePrint = typeSettingsProperties.getProperty(
LayoutTypePortletConstants.MODE_PRINT);
layoutTypePortlet.setStateMax(stateMax);
layoutTypePortlet.setStateMin(stateMin);
layoutTypePortlet.setModeAbout(modeAbout);
layoutTypePortlet.setModeConfig(modeConfig);
layoutTypePortlet.setModeEdit(modeEdit);
layoutTypePortlet.setModeEditDefaults(modeEditDefaults);
layoutTypePortlet.setModeEditGuest(modeEditGuest);
layoutTypePortlet.setModeHelp(modeHelp);
layoutTypePortlet.setModePreview(modePreview);
layoutTypePortlet.setModePrint(modePrint);
}
}
request.setAttribute(WebKeys.LAYOUT, layout);
request.setAttribute(WebKeys.LAYOUTS, layouts);
if (layout.isPrivateLayout()) {
permissionChecker.setCheckGuest(false);
}
}
// Scope
long scopeGroupId = PortalUtil.getScopeGroupId(request);
long parentGroupId = PortalUtil.getParentGroupId(scopeGroupId);
// Theme and color scheme
Theme theme = null;
ColorScheme colorScheme = null;
boolean wapTheme = BrowserSnifferUtil.isWap(request);
System.out.println("isWap()"+wapTheme);
//uses WAP theme as a mobile theme
boolean mobileTheme = BrowserSnifferUtil.isMobile(request);
System.out.println("isMobile()"+mobileTheme);
if ((layout != null) && group.isControlPanel()) {
String themeId = PrefsPropsUtil.getString(
companyId, PropsKeys.CONTROL_PANEL_LAYOUT_REGULAR_THEME_ID);
String colorSchemeId =
ColorSchemeImpl.getDefaultRegularColorSchemeId();
theme = ThemeLocalServiceUtil.getTheme(
companyId, themeId, wapTheme);
colorScheme = ThemeLocalServiceUtil.getColorScheme(
companyId, theme.getThemeId(), colorSchemeId, wapTheme);
if (!wapTheme && theme.isWapTheme()) {
theme = ThemeLocalServiceUtil.getTheme(
companyId,
PropsValues.CONTROL_PANEL_LAYOUT_REGULAR_THEME_ID, false);
colorScheme = ThemeLocalServiceUtil.getColorScheme(
companyId, theme.getThemeId(), colorSchemeId, false);
}
request.setAttribute(WebKeys.THEME, theme);
request.setAttribute(WebKeys.COLOR_SCHEME, colorScheme);
}
boolean themeCssFastLoad = SessionParamUtil.getBoolean(
request, "css_fast_load", PropsValues.THEME_CSS_FAST_LOAD);
boolean themeImagesFastLoad = SessionParamUtil.getBoolean(
request, "images_fast_load", PropsValues.THEME_IMAGES_FAST_LOAD);
boolean themeJsBarebone = PropsValues.JAVASCRIPT_BAREBONE_ENABLED;
if (themeJsBarebone) {
if (signedIn) {
themeJsBarebone = false;
}
}
boolean themeJsFastLoad = SessionParamUtil.getBoolean(
request, "js_fast_load", PropsValues.JAVASCRIPT_FAST_LOAD);
String lifecycle = ParamUtil.getString(request, "p_p_lifecycle", "0");
lifecycle = ParamUtil.getString(request, "p_t_lifecycle", lifecycle);
boolean isolated = ParamUtil.getBoolean(request, "p_p_isolated");
String facebookCanvasPageURL = (String)request.getAttribute(
WebKeys.FACEBOOK_CANVAS_PAGE_URL);
boolean widget = false;
Boolean widgetObj = (Boolean)request.getAttribute(WebKeys.WIDGET);
if (widgetObj != null) {
widget = widgetObj.booleanValue();
}
// Theme display
ThemeDisplay themeDisplay = ThemeDisplayFactory.create();
// Set the CDN host, portal URL, and Facebook application ID first
// because other methods (setLookAndFeel) depend on them being set
themeDisplay.setCDNHost(cdnHost);
themeDisplay.setPortalURL(portalURL);
themeDisplay.setFacebookCanvasPageURL(facebookCanvasPageURL);
themeDisplay.setWidget(widget);
themeDisplay.setCompany(company);
themeDisplay.setCompanyLogo(companyLogo);
themeDisplay.setCompanyLogoHeight(companyLogoHeight);
themeDisplay.setCompanyLogoWidth(companyLogoWidth);
themeDisplay.setRealCompanyLogo(realCompanyLogo);
themeDisplay.setRealCompanyLogoHeight(realCompanyLogoHeight);
themeDisplay.setRealCompanyLogoWidth(realCompanyLogoWidth);
themeDisplay.setUser(user);
themeDisplay.setRealUser(realUser);
themeDisplay.setDoAsUserId(doAsUserId);
themeDisplay.setDoAsUserLanguageId(doAsUserLanguageId);
themeDisplay.setDoAsGroupId(doAsGroupId);
themeDisplay.setRefererPlid(refererPlid);
themeDisplay.setControlPanelCategory(controlPanelCategory);
themeDisplay.setLayoutSet(layoutSet);
themeDisplay.setLayoutSetLogo(layoutSetLogo);
themeDisplay.setLayout(layout);
themeDisplay.setLayouts(layouts);
themeDisplay.setUnfilteredLayouts(unfilteredLayouts);
themeDisplay.setPlid(plid);
themeDisplay.setLayoutTypePortlet(layoutTypePortlet);
themeDisplay.setScopeGroupId(scopeGroupId);
themeDisplay.setParentGroupId(parentGroupId);
themeDisplay.setSignedIn(signedIn);
themeDisplay.setPermissionChecker(permissionChecker);
themeDisplay.setLocale(locale);
themeDisplay.setLanguageId(LocaleUtil.toLanguageId(locale));
themeDisplay.setI18nLanguageId(i18nLanguageId);
themeDisplay.setI18nPath(i18nPath);
themeDisplay.setTimeZone(timeZone);
themeDisplay.setLookAndFeel(theme, colorScheme);
themeDisplay.setThemeCssFastLoad(themeCssFastLoad);
themeDisplay.setThemeImagesFastLoad(themeImagesFastLoad);
themeDisplay.setThemeJsBarebone(themeJsBarebone);
themeDisplay.setThemeJsFastLoad(themeJsFastLoad);
themeDisplay.setServerName(request.getServerName());
themeDisplay.setServerPort(request.getServerPort());
themeDisplay.setSecure(PortalUtil.isSecure(request));
themeDisplay.setLifecycle(lifecycle);
themeDisplay.setLifecycleAction(lifecycle.equals("1"));
themeDisplay.setLifecycleRender(lifecycle.equals("0"));
themeDisplay.setLifecycleResource(lifecycle.equals("2"));
themeDisplay.setStateExclusive(LiferayWindowState.isExclusive(request));
themeDisplay.setStateMaximized(LiferayWindowState.isMaximized(request));
themeDisplay.setStatePopUp(LiferayWindowState.isPopUp(request));
themeDisplay.setIsolated(isolated);
themeDisplay.setPathApplet(contextPath.concat("/applets"));
themeDisplay.setPathCms(contextPath.concat("/cms"));
themeDisplay.setPathContext(contextPath);
themeDisplay.setPathFlash(contextPath.concat("/flash"));
themeDisplay.setPathFriendlyURLPrivateGroup(
friendlyURLPrivateGroupPath);
themeDisplay.setPathFriendlyURLPrivateUser(friendlyURLPrivateUserPath);
themeDisplay.setPathFriendlyURLPublic(friendlyURLPublicPath);
themeDisplay.setPathImage(imagePath);
themeDisplay.setPathJavaScript(
cdnHost.concat(contextPath).concat("/html/js"));
themeDisplay.setPathMain(mainPath);
themeDisplay.setPathSound(contextPath.concat("/html/sound"));
// Icons
themeDisplay.setShowAddContentIcon(false);
themeDisplay.setShowControlPanelIcon(signedIn);
themeDisplay.setShowHomeIcon(true);
themeDisplay.setShowMyAccountIcon(signedIn);
themeDisplay.setShowPageSettingsIcon(false);
themeDisplay.setShowPortalIcon(true);
themeDisplay.setShowSignInIcon(!signedIn);
themeDisplay.setShowSignOutIcon(signedIn);
boolean showSiteContentIcon = false;
long controlPanelPlid = 0;
if (signedIn) {
Group controlPanelGroup = GroupLocalServiceUtil.getGroup(
companyId, GroupConstants.CONTROL_PANEL);
controlPanelPlid = LayoutLocalServiceUtil.getDefaultPlid(
controlPanelGroup.getGroupId(), true);
List<Portlet> siteContentPortlets =
PortalUtil.getControlPanelPortlets(
PortletCategoryKeys.CONTENT, themeDisplay);
Portlet groupPagesPortlet = PortletLocalServiceUtil.getPortletById(
PortletKeys.GROUP_PAGES);
siteContentPortlets.remove(groupPagesPortlet);
Portlet siteMembershipsAdminPortlet =
PortletLocalServiceUtil.getPortletById(
PortletKeys.SITE_MEMBERSHIPS_ADMIN);
siteContentPortlets.remove(siteMembershipsAdminPortlet);
Portlet siteSettingsPortlet =
PortletLocalServiceUtil.getPortletById(
PortletKeys.SITE_SETTINGS);
siteContentPortlets.remove(siteSettingsPortlet);
showSiteContentIcon = PortletPermissionUtil.contains(
permissionChecker, scopeGroupId, controlPanelPlid,
siteContentPortlets, ActionKeys.VIEW);
}
themeDisplay.setShowSiteContentIcon(showSiteContentIcon);
themeDisplay.setShowStagingIcon(false);
// Session
if (PropsValues.SESSION_ENABLE_URL_WITH_SESSION_ID &&
!CookieKeys.hasSessionId(request)) {
themeDisplay.setAddSessionIdToURL(true);
themeDisplay.setSessionId(session.getId());
}
// URLs
String urlControlPanel = friendlyURLPrivateGroupPath.concat(
GroupConstants.CONTROL_PANEL_FRIENDLY_URL);
if (Validator.isNotNull(doAsUserId)) {
urlControlPanel = HttpUtil.addParameter(
urlControlPanel, "doAsUserId", doAsUserId);
}
if (scopeGroupId > 0) {
urlControlPanel = HttpUtil.addParameter(
urlControlPanel, "doAsGroupId", scopeGroupId);
}
if (refererPlid > 0) {
urlControlPanel = HttpUtil.addParameter(
urlControlPanel, "refererPlid", refererPlid);
}
else if (plid > 0) {
urlControlPanel = HttpUtil.addParameter(
urlControlPanel, "refererPlid", plid);
}
if (themeDisplay.isAddSessionIdToURL()) {
urlControlPanel = PortalUtil.getURLWithSessionId(
urlControlPanel, session.getId());
}
themeDisplay.setURLControlPanel(urlControlPanel);
String siteContentURL = urlControlPanel;
siteContentURL = HttpUtil.addParameter(
siteContentURL, "controlPanelCategory",
PortletCategoryKeys.CONTENT);
themeDisplay.setURLSiteContent(siteContentURL);
String currentURL = PortalUtil.getCurrentURL(request);
themeDisplay.setURLCurrent(currentURL);
String urlHome = PortalUtil.getHomeURL(request);
themeDisplay.setURLHome(urlHome);
if (layout != null) {
if (layout.isTypePortlet()) {
boolean freeformLayout =
layoutTypePortlet.getLayoutTemplateId().equals("freeform");
themeDisplay.setFreeformLayout(freeformLayout);
if (hasUpdateLayoutPermission) {
themeDisplay.setShowAddContentIconPermission(true);
if (!LiferayWindowState.isMaximized(request)) {
themeDisplay.setShowAddContentIcon(true);
}
themeDisplay.setShowLayoutTemplatesIcon(true);
if (!group.isUser()) {
themeDisplay.setShowPageCustomizationIcon(true);
}
themeDisplay.setURLAddContent(
"Liferay.LayoutConfiguration.toggle('".concat(
PortletKeys.LAYOUT_CONFIGURATION).concat("');"));
themeDisplay.setURLLayoutTemplates(
"Liferay.LayoutConfiguration.showTemplates();");
}
if (hasCustomizeLayoutPermission && customizedView) {
themeDisplay.setShowAddContentIconPermission(true);
if (!LiferayWindowState.isMaximized(request)) {
themeDisplay.setShowAddContentIcon(true);
}
themeDisplay.setURLAddContent(
"Liferay.LayoutConfiguration.toggle('".concat(
PortletKeys.LAYOUT_CONFIGURATION).concat("');"));
}
}
if (signedIn) {
if (group.isUser()) {
if ((layout.isPrivateLayout() &&
!PropsValues.LAYOUT_USER_PRIVATE_LAYOUTS_MODIFIABLE) ||
(layout.isPublicLayout() &&
!PropsValues.LAYOUT_USER_PUBLIC_LAYOUTS_MODIFIABLE)) {
hasUpdateLayoutPermission = false;
}
}
}
if (hasUpdateLayoutPermission) {
themeDisplay.setShowPageSettingsIcon(true);
LiferayPortletURL pageSettingsURL = new PortletURLImpl(
request, PortletKeys.LAYOUTS_ADMIN, controlPanelPlid,
PortletRequest.RENDER_PHASE);
pageSettingsURL.setControlPanelCategory(
_CONTROL_PANEL_CATEGORY_PORTLET_PREFIX +
PortletKeys.LAYOUTS_ADMIN);
pageSettingsURL.setParameter(
"struts_action", "/layouts_admin/edit_layouts");
if (layout.isPrivateLayout()) {
pageSettingsURL.setParameter("tabs1", "private-pages");
}
else {
pageSettingsURL.setParameter("tabs1", "public-pages");
}
pageSettingsURL.setParameter("closeRedirect", currentURL);
pageSettingsURL.setParameter(
"groupId", String.valueOf(scopeGroupId));
pageSettingsURL.setParameter("selPlid", String.valueOf(plid));
pageSettingsURL.setPortletMode(PortletMode.VIEW);
pageSettingsURL.setWindowState(LiferayWindowState.POP_UP);
themeDisplay.setURLPageSettings(pageSettingsURL);
boolean site = group.isSite();
if (!site && group.isStagingGroup()) {
Group liveGroup = group.getLiveGroup();
site = liveGroup.isSite();
}
if (site &&
GroupPermissionUtil.contains(
permissionChecker, scopeGroupId,
ActionKeys.ASSIGN_MEMBERS)) {
themeDisplay.setShowManageSiteMembershipsIcon(true);
LiferayPortletURL manageSiteMembershipsURL =
new PortletURLImpl(
request, PortletKeys.SITE_MEMBERSHIPS_ADMIN,
controlPanelPlid, PortletRequest.RENDER_PHASE);
manageSiteMembershipsURL.setControlPanelCategory(
_CONTROL_PANEL_CATEGORY_PORTLET_PREFIX +
PortletKeys.SITE_MEMBERSHIPS_ADMIN);
manageSiteMembershipsURL.setParameter(
"struts_action", "/sites_admin/edit_site_assignments");
manageSiteMembershipsURL.setParameter(
"groupId", String.valueOf(scopeGroupId));
manageSiteMembershipsURL.setParameter(
"selPlid", String.valueOf(plid));
manageSiteMembershipsURL.setPortletMode(PortletMode.VIEW);
manageSiteMembershipsURL.setWindowState(
LiferayWindowState.POP_UP);
themeDisplay.setURLManageSiteMemberships(
manageSiteMembershipsURL);
}
else {
themeDisplay.setShowManageSiteMembershipsIcon(false);
}
}
boolean hasAddLayoutGroupPermission =
GroupPermissionUtil.contains(
permissionChecker, scopeGroupId, ActionKeys.ADD_LAYOUT);
boolean hasAddLayoutLayoutPermission =
LayoutPermissionUtil.contains(
permissionChecker, layout, ActionKeys.ADD_LAYOUT);
boolean hasManageLayoutsGroupPermission =
GroupPermissionUtil.contains(
permissionChecker, scopeGroupId, ActionKeys.MANAGE_LAYOUTS);
boolean hasManageStagingPermission = GroupPermissionUtil.contains(
permissionChecker, scopeGroupId, ActionKeys.MANAGE_STAGING);
boolean hasPublishStagingPermission = GroupPermissionUtil.contains(
permissionChecker, scopeGroupId, ActionKeys.PUBLISH_STAGING);
boolean hasUpdateGroupPermission = GroupPermissionUtil.contains(
permissionChecker, scopeGroupId, ActionKeys.UPDATE);
boolean hasViewStagingPermission = GroupPermissionUtil.contains(
permissionChecker, scopeGroupId, ActionKeys.VIEW_STAGING);
if (!group.isControlPanel() && !group.isUser() &&
!group.isUserGroup() && hasUpdateGroupPermission) {
themeDisplay.setShowSiteSettingsIcon(true);
LiferayPortletURL siteSettingsURL = new PortletURLImpl(
request, PortletKeys.SITE_SETTINGS, controlPanelPlid,
PortletRequest.RENDER_PHASE);
siteSettingsURL.setControlPanelCategory(
_CONTROL_PANEL_CATEGORY_PORTLET_PREFIX +
PortletKeys.SITE_SETTINGS);
siteSettingsURL.setParameter(
"struts_action", "/sites_admin/edit_site");
siteSettingsURL.setParameter("closeRedirect", currentURL);
siteSettingsURL.setParameter(
"groupId", String.valueOf(scopeGroupId));
siteSettingsURL.setPortletMode(PortletMode.VIEW);
siteSettingsURL.setWindowState(LiferayWindowState.POP_UP);
themeDisplay.setURLSiteSettings(siteSettingsURL);
}
if (!group.isLayoutPrototype() &&
(hasAddLayoutGroupPermission || hasAddLayoutLayoutPermission ||
hasManageLayoutsGroupPermission || hasUpdateGroupPermission)) {
themeDisplay.setShowSiteMapSettingsIcon(true);
LiferayPortletURL siteMapSettingsURL = new PortletURLImpl(
request, PortletKeys.LAYOUTS_ADMIN, controlPanelPlid,
PortletRequest.RENDER_PHASE);
siteMapSettingsURL.setControlPanelCategory(
_CONTROL_PANEL_CATEGORY_PORTLET_PREFIX +
PortletKeys.LAYOUTS_ADMIN);
siteMapSettingsURL.setParameter(
"struts_action", "/layouts_admin/edit_layouts");
if (layout.isPrivateLayout()) {
siteMapSettingsURL.setParameter("tabs1", "private-pages");
}
else {
siteMapSettingsURL.setParameter("tabs1", "public-pages");
}
siteMapSettingsURL.setParameter("closeRedirect", currentURL);
siteMapSettingsURL.setParameter(
"groupId", String.valueOf(scopeGroupId));
siteMapSettingsURL.setPortletMode(PortletMode.VIEW);
siteMapSettingsURL.setWindowState(LiferayWindowState.POP_UP);
themeDisplay.setURLSiteMapSettings(siteMapSettingsURL);
}
if (group.hasStagingGroup() && !group.isStagingGroup()) {
themeDisplay.setShowAddContentIcon(false);
themeDisplay.setShowLayoutTemplatesIcon(false);
themeDisplay.setShowPageSettingsIcon(false);
themeDisplay.setURLPublishToLive(null);
}
if (group.isControlPanel()) {
themeDisplay.setShowPageSettingsIcon(false);
themeDisplay.setURLPublishToLive(null);
}
// LEP-4987
if (group.isStaged() || group.isStagingGroup()) {
if (hasManageStagingPermission || hasPublishStagingPermission ||
hasUpdateLayoutPermission || hasViewStagingPermission) {
themeDisplay.setShowStagingIcon(true);
}
if (hasPublishStagingPermission) {
PortletURL publishToLiveURL = new PortletURLImpl(
request, PortletKeys.LAYOUTS_ADMIN, plid,
PortletRequest.RENDER_PHASE);
publishToLiveURL.setParameter(
"struts_action", "/layouts_admin/publish_layouts");
if (layout.isPrivateLayout()) {
publishToLiveURL.setParameter("tabs1", "private-pages");
}
else {
publishToLiveURL.setParameter("tabs1", "public-pages");
}
publishToLiveURL.setParameter("pagesRedirect", currentURL);
publishToLiveURL.setParameter(
"groupId", String.valueOf(scopeGroupId));
publishToLiveURL.setParameter(
"selPlid", String.valueOf(plid));
publishToLiveURL.setPortletMode(PortletMode.VIEW);
publishToLiveURL.setWindowState(
LiferayWindowState.EXCLUSIVE);
themeDisplay.setURLPublishToLive(publishToLiveURL);
}
}
PortletURLImpl myAccountURL = new PortletURLImpl(
request, PortletKeys.MY_ACCOUNT, controlPanelPlid,
PortletRequest.RENDER_PHASE);
if (scopeGroupId > 0) {
myAccountURL.setDoAsGroupId(scopeGroupId);
}
myAccountURL.setParameter("struts_action", "/my_account/edit_user");
myAccountURL.setPortletMode(PortletMode.VIEW);
if (refererPlid > 0) {
myAccountURL.setRefererPlid(refererPlid);
}
else {
myAccountURL.setRefererPlid(plid);
}
myAccountURL.setWindowState(WindowState.MAXIMIZED);
themeDisplay.setURLMyAccount(myAccountURL);
}
if ((!user.isActive()) ||
(PrefsPropsUtil.getBoolean(
companyId, PropsKeys.TERMS_OF_USE_REQUIRED) &&
!user.isAgreedToTermsOfUse())) {
themeDisplay.setShowAddContentIcon(false);
themeDisplay.setShowMyAccountIcon(false);
themeDisplay.setShowPageSettingsIcon(false);
}
if (group.isLayoutPrototype()) {
themeDisplay.setShowControlPanelIcon(false);
themeDisplay.setShowHomeIcon(false);
themeDisplay.setShowManageSiteMembershipsIcon(false);
themeDisplay.setShowMyAccountIcon(false);
themeDisplay.setShowPageCustomizationIcon(false);
themeDisplay.setShowPageSettingsIcon(true);
themeDisplay.setShowPortalIcon(false);
themeDisplay.setShowSignInIcon(false);
themeDisplay.setShowSignOutIcon(false);
themeDisplay.setShowSiteContentIcon(false);
themeDisplay.setShowSiteSettingsIcon(false);
themeDisplay.setShowStagingIcon(false);
}
if (group.isLayoutSetPrototype()) {
themeDisplay.setShowPageCustomizationIcon(false);
themeDisplay.setShowSiteSettingsIcon(false);
}
if (group.hasStagingGroup() && !group.isStagingGroup()) {
themeDisplay.setShowLayoutTemplatesIcon(false);
themeDisplay.setShowPageCustomizationIcon(false);
themeDisplay.setShowPageSettingsIcon(false);
themeDisplay.setShowSiteContentIcon(false);
themeDisplay.setShowSiteMapSettingsIcon(false);
themeDisplay.setShowSiteSettingsIcon(false);
}
themeDisplay.setURLPortal(portalURL.concat(contextPath));
String urlSignIn = mainPath.concat("/portal/login");
if (layout != null) {
urlSignIn = HttpUtil.addParameter(
urlSignIn, "p_l_id", layout.getPlid());
}
themeDisplay.setURLSignIn(urlSignIn);
themeDisplay.setURLSignOut(mainPath.concat("/portal/logout"));
PortletURL updateManagerURL = new PortletURLImpl(
request, PortletKeys.UPDATE_MANAGER, plid,
PortletRequest.RENDER_PHASE);
updateManagerURL.setParameter("struts_action", "/update_manager/view");
updateManagerURL.setPortletMode(PortletMode.VIEW);
updateManagerURL.setWindowState(WindowState.MAXIMIZED);
themeDisplay.setURLUpdateManager(updateManagerURL);
return themeDisplay;
}
@Override
public void run(HttpServletRequest request, HttpServletResponse response)
throws ActionException {
StopWatch stopWatch = null;
if (_log.isDebugEnabled()) {
stopWatch = new StopWatch();
stopWatch.start();
}
try {
servicePre(request, response);
}
catch (Exception e) {
throw new ActionException(e);
}
if (_log.isDebugEnabled()) {
_log.debug("Running takes " + stopWatch.getTime() + " ms");
}
}
protected void addDefaultLayoutsByLAR(
long userId, long groupId, boolean privateLayout, File larFile)
throws PortalException, SystemException {
Map<String, String[]> parameterMap = new HashMap<String, String[]>();
parameterMap.put(
PortletDataHandlerKeys.PERMISSIONS,
new String[] {Boolean.TRUE.toString()});
parameterMap.put(
PortletDataHandlerKeys.PORTLET_DATA,
new String[] {Boolean.TRUE.toString()});
parameterMap.put(
PortletDataHandlerKeys.PORTLET_DATA_CONTROL_DEFAULT,
new String[] {Boolean.TRUE.toString()});
parameterMap.put(
PortletDataHandlerKeys.PORTLET_SETUP,
new String[] {Boolean.TRUE.toString()});
parameterMap.put(
PortletDataHandlerKeys.USER_PERMISSIONS,
new String[] {Boolean.FALSE.toString()});
LayoutLocalServiceUtil.importLayouts(
userId, groupId, privateLayout, parameterMap, larFile);
}
protected void addDefaultUserPrivateLayoutByProperties(
long userId, long groupId)
throws PortalException, SystemException {
String friendlyURL = getFriendlyURL(
PropsValues.DEFAULT_USER_PRIVATE_LAYOUT_FRIENDLY_URL);
ServiceContext serviceContext = new ServiceContext();
Layout layout = LayoutLocalServiceUtil.addLayout(
userId, groupId, true, LayoutConstants.DEFAULT_PARENT_LAYOUT_ID,
PropsValues.DEFAULT_USER_PRIVATE_LAYOUT_NAME, StringPool.BLANK,
StringPool.BLANK, LayoutConstants.TYPE_PORTLET, false, friendlyURL,
serviceContext);
LayoutTypePortlet layoutTypePortlet =
(LayoutTypePortlet)layout.getLayoutType();
layoutTypePortlet.setLayoutTemplateId(
0, PropsValues.DEFAULT_USER_PRIVATE_LAYOUT_TEMPLATE_ID, false);
for (int i = 0; i < 10; i++) {
String columnId = "column-" + i;
String portletIds = PropsUtil.get(
PropsKeys.DEFAULT_USER_PRIVATE_LAYOUT_COLUMN + i);
String[] portletIdsArray = StringUtil.split(portletIds);
layoutTypePortlet.addPortletIds(
0, portletIdsArray, columnId, false);
}
LayoutLocalServiceUtil.updateLayout(
layout.getGroupId(), layout.isPrivateLayout(), layout.getLayoutId(),
layout.getTypeSettings());
boolean updateLayoutSet = false;
LayoutSet layoutSet = layout.getLayoutSet();
if (Validator.isNotNull(
PropsValues.DEFAULT_USER_PRIVATE_LAYOUT_REGULAR_THEME_ID)) {
layoutSet.setThemeId(
PropsValues.DEFAULT_USER_PRIVATE_LAYOUT_REGULAR_THEME_ID);
updateLayoutSet = true;
}
if (Validator.isNotNull(
PropsValues.
DEFAULT_USER_PRIVATE_LAYOUT_REGULAR_COLOR_SCHEME_ID)) {
layoutSet.setColorSchemeId(
PropsValues.
DEFAULT_USER_PRIVATE_LAYOUT_REGULAR_COLOR_SCHEME_ID);
updateLayoutSet = true;
}
if (Validator.isNotNull(
PropsValues.DEFAULT_USER_PRIVATE_LAYOUT_WAP_THEME_ID)) {
layoutSet.setWapThemeId(
PropsValues.DEFAULT_USER_PRIVATE_LAYOUT_WAP_THEME_ID);
updateLayoutSet = true;
}
if (Validator.isNotNull(
PropsValues.DEFAULT_USER_PRIVATE_LAYOUT_WAP_COLOR_SCHEME_ID)) {
layoutSet.setWapColorSchemeId(
PropsValues.DEFAULT_USER_PRIVATE_LAYOUT_WAP_COLOR_SCHEME_ID);
updateLayoutSet = true;
}
if (updateLayoutSet) {
LayoutSetLocalServiceUtil.updateLayoutSet(layoutSet);
}
}
protected void addDefaultUserPrivateLayouts(User user)
throws PortalException, SystemException {
Group userGroup = user.getGroup();
if (privateLARFile != null) {
addDefaultLayoutsByLAR(
user.getUserId(), userGroup.getGroupId(), true, privateLARFile);
}
else {
addDefaultUserPrivateLayoutByProperties(
user.getUserId(), userGroup.getGroupId());
}
}
protected void addDefaultUserPublicLayoutByProperties(
long userId, long groupId)
throws PortalException, SystemException {
String friendlyURL = getFriendlyURL(
PropsValues.DEFAULT_USER_PUBLIC_LAYOUT_FRIENDLY_URL);
ServiceContext serviceContext = new ServiceContext();
Layout layout = LayoutLocalServiceUtil.addLayout(
userId, groupId, false, LayoutConstants.DEFAULT_PARENT_LAYOUT_ID,
PropsValues.DEFAULT_USER_PUBLIC_LAYOUT_NAME, StringPool.BLANK,
StringPool.BLANK, LayoutConstants.TYPE_PORTLET, false, friendlyURL,
serviceContext);
LayoutTypePortlet layoutTypePortlet =
(LayoutTypePortlet)layout.getLayoutType();
layoutTypePortlet.setLayoutTemplateId(
0, PropsValues.DEFAULT_USER_PUBLIC_LAYOUT_TEMPLATE_ID, false);
for (int i = 0; i < 10; i++) {
String columnId = "column-" + i;
String portletIds = PropsUtil.get(
PropsKeys.DEFAULT_USER_PUBLIC_LAYOUT_COLUMN + i);
String[] portletIdsArray = StringUtil.split(portletIds);
layoutTypePortlet.addPortletIds(
0, portletIdsArray, columnId, false);
}
LayoutLocalServiceUtil.updateLayout(
layout.getGroupId(), layout.isPrivateLayout(), layout.getLayoutId(),
layout.getTypeSettings());
boolean updateLayoutSet = false;
LayoutSet layoutSet = layout.getLayoutSet();
if (Validator.isNotNull(
PropsValues.DEFAULT_USER_PUBLIC_LAYOUT_REGULAR_THEME_ID)) {
layoutSet.setThemeId(
PropsValues.DEFAULT_USER_PUBLIC_LAYOUT_REGULAR_THEME_ID);
updateLayoutSet = true;
}
if (Validator.isNotNull(
PropsValues.
DEFAULT_USER_PUBLIC_LAYOUT_REGULAR_COLOR_SCHEME_ID)) {
layoutSet.setColorSchemeId(
PropsValues.DEFAULT_USER_PUBLIC_LAYOUT_REGULAR_COLOR_SCHEME_ID);
updateLayoutSet = true;
}
if (Validator.isNotNull(
PropsValues.DEFAULT_USER_PUBLIC_LAYOUT_WAP_THEME_ID)) {
layoutSet.setWapThemeId(
PropsValues.DEFAULT_USER_PUBLIC_LAYOUT_WAP_THEME_ID);
updateLayoutSet = true;
}
if (Validator.isNotNull(
PropsValues.DEFAULT_USER_PUBLIC_LAYOUT_WAP_COLOR_SCHEME_ID)) {
layoutSet.setWapColorSchemeId(
PropsValues.DEFAULT_USER_PUBLIC_LAYOUT_WAP_COLOR_SCHEME_ID);
updateLayoutSet = true;
}
if (updateLayoutSet) {
LayoutSetLocalServiceUtil.updateLayoutSet(layoutSet);
}
}
protected void addDefaultUserPublicLayouts(User user)
throws PortalException, SystemException {
Group userGroup = user.getGroup();
if (publicLARFile != null) {
addDefaultLayoutsByLAR(
user.getUserId(), userGroup.getGroupId(), false, publicLARFile);
}
else {
addDefaultUserPublicLayoutByProperties(
user.getUserId(), userGroup.getGroupId());
}
}
protected void deleteDefaultUserPrivateLayouts(User user)
throws PortalException, SystemException {
Group userGroup = user.getGroup();
ServiceContext serviceContext = new ServiceContext();
LayoutLocalServiceUtil.deleteLayouts(
userGroup.getGroupId(), true, serviceContext);
}
protected void deleteDefaultUserPublicLayouts(User user)
throws PortalException, SystemException {
Group userGroup = user.getGroup();
ServiceContext serviceContext = new ServiceContext();
LayoutLocalServiceUtil.deleteLayouts(
userGroup.getGroupId(), false, serviceContext);
}
protected Object[] getDefaultLayout(
HttpServletRequest request, User user, boolean signedIn)
throws PortalException, SystemException {
// Check the virtual host
LayoutSet layoutSet = (LayoutSet)request.getAttribute(
WebKeys.VIRTUAL_HOST_LAYOUT_SET);
if (layoutSet != null) {
List<Layout> layouts = LayoutLocalServiceUtil.getLayouts(
layoutSet.getGroupId(), layoutSet.isPrivateLayout(),
LayoutConstants.DEFAULT_PARENT_LAYOUT_ID);
if (layouts.size() > 0) {
Layout layout = layouts.get(0);
return new Object[] {layout, layouts};
}
}
Layout layout = null;
List<Layout> layouts = null;
if (signedIn) {
// Check the user's personal layouts
Group userGroup = user.getGroup();
layouts = LayoutLocalServiceUtil.getLayouts(
userGroup.getGroupId(), true,
LayoutConstants.DEFAULT_PARENT_LAYOUT_ID);
if (layouts.size() == 0) {
layouts = LayoutLocalServiceUtil.getLayouts(
userGroup.getGroupId(), false,
LayoutConstants.DEFAULT_PARENT_LAYOUT_ID);
}
if (layouts.size() > 0) {
layout = layouts.get(0);
}
// Check the user's sites
if (layout == null) {
LinkedHashMap<String, Object> groupParams =
new LinkedHashMap<String, Object>();
groupParams.put("usersGroups", new Long(user.getUserId()));
List<Group> groups = GroupLocalServiceUtil.search(
user.getCompanyId(), null, null, groupParams,
QueryUtil.ALL_POS, QueryUtil.ALL_POS);
for (Group group : groups) {
layouts = LayoutLocalServiceUtil.getLayouts(
group.getGroupId(), true,
LayoutConstants.DEFAULT_PARENT_LAYOUT_ID);
if (layouts.size() == 0) {
layouts = LayoutLocalServiceUtil.getLayouts(
group.getGroupId(), false,
LayoutConstants.DEFAULT_PARENT_LAYOUT_ID);
}
if (layouts.size() > 0) {
layout = layouts.get(0);
break;
}
}
}
}
if (layout == null) {
// Check the Guest site
Group guestGroup = GroupLocalServiceUtil.getGroup(
user.getCompanyId(), GroupConstants.GUEST);
layouts = LayoutLocalServiceUtil.getLayouts(
guestGroup.getGroupId(), false,
LayoutConstants.DEFAULT_PARENT_LAYOUT_ID);
if (layouts.size() > 0) {
layout = layouts.get(0);
}
}
return new Object[] {layout, layouts};
}
protected String getFriendlyURL(String friendlyURL) {
friendlyURL = GetterUtil.getString(friendlyURL);
return FriendlyURLNormalizerUtil.normalize(friendlyURL);
}
protected Object[] getViewableLayouts(
HttpServletRequest request, User user,
PermissionChecker permissionChecker, Layout layout,
List<Layout> layouts)
throws PortalException, SystemException {
if ((layouts == null) || layouts.isEmpty()) {
return new Object[] {layout, layouts};
}
Group group = layout.getGroup();
boolean hasViewLayoutPermission = false;
boolean hasViewStagingPermission =
(group.isStagingGroup() || group.isStagedRemotely()) &&
GroupPermissionUtil.contains(
permissionChecker, group.getGroupId(),
ActionKeys.VIEW_STAGING);
if (LayoutPermissionUtil.contains(
permissionChecker, layout, false, ActionKeys.VIEW) ||
hasViewStagingPermission) {
hasViewLayoutPermission = true;
}
List<Layout> accessibleLayouts = new ArrayList<Layout>();
for (int i = 0; i < layouts.size(); i++) {
Layout curLayout = layouts.get(i);
if (!curLayout.isHidden() &&
(LayoutPermissionUtil.contains(
permissionChecker, curLayout, false, ActionKeys.VIEW) ||
hasViewStagingPermission)) {
if (accessibleLayouts.isEmpty() && !hasViewLayoutPermission) {
layout = curLayout;
}
accessibleLayouts.add(curLayout);
}
}
if (accessibleLayouts.isEmpty()) {
layouts = null;
if (!hasViewLayoutPermission) {
SessionErrors.add(
request, LayoutPermissionException.class.getName());
}
}
else {
layouts = accessibleLayouts;
}
return new Object[] {layout, layouts};
}
protected Boolean hasPowerUserRole(User user) throws Exception {
return RoleLocalServiceUtil.hasUserRole(
user.getUserId(), user.getCompanyId(), RoleConstants.POWER_USER,
true);
}
protected void initImportLARFiles() {
String privateLARFileName =
PropsValues.DEFAULT_USER_PRIVATE_LAYOUTS_LAR;
if (_log.isDebugEnabled()) {
_log.debug("Reading private LAR file " + privateLARFileName);
}
if (Validator.isNotNull(privateLARFileName)) {
privateLARFile = new File(privateLARFileName);
if (!privateLARFile.exists()) {
_log.error(
"Private LAR file " + privateLARFile + " does not exist");
privateLARFile = null;
}
else {
if (_log.isDebugEnabled()) {
_log.debug("Using private LAR file " + privateLARFileName);
}
}
}
String publicLARFileName = PropsValues.DEFAULT_USER_PUBLIC_LAYOUTS_LAR;
if (_log.isDebugEnabled()) {
_log.debug("Reading public LAR file " + publicLARFileName);
}
if (Validator.isNotNull(publicLARFileName)) {
publicLARFile = new File(publicLARFileName);
if (!publicLARFile.exists()) {
_log.error(
"Public LAR file " + publicLARFile + " does not exist");
publicLARFile = null;
}
else {
if (_log.isDebugEnabled()) {
_log.debug("Using public LAR file " + publicLARFileName);
}
}
}
}
protected boolean isLoginRequest(HttpServletRequest request) {
String requestURI = request.getRequestURI();
String mainPath = PortalUtil.getPathMain();
if (requestURI.startsWith(mainPath.concat("/portal/login"))) {
return true;
}
else {
return false;
}
}
/**
* @deprecated
*/
protected boolean isViewableCommunity(
User user, long groupId, boolean privateLayout,
PermissionChecker permissionChecker)
throws PortalException, SystemException {
return LayoutPermissionUtil.contains(
permissionChecker, groupId, privateLayout, 0, ActionKeys.VIEW);
}
/**
* @deprecated
*/
protected boolean isViewableGroup(
User user, long groupId, boolean privateLayout, long layoutId,
String controlPanelCategory, PermissionChecker permissionChecker)
throws PortalException, SystemException {
return LayoutPermissionUtil.contains(
permissionChecker, groupId, privateLayout, layoutId,
controlPanelCategory, ActionKeys.VIEW);
}
protected List<Layout> mergeAdditionalLayouts(
HttpServletRequest request, User user,
PermissionChecker permissionChecker, Layout layout,
List<Layout> layouts)
throws PortalException, SystemException {
if ((layout == null) || layout.isPrivateLayout()) {
return layouts;
}
long layoutGroupId = layout.getGroupId();
Group guestGroup = GroupLocalServiceUtil.getGroup(
user.getCompanyId(), GroupConstants.GUEST);
if (layoutGroupId != guestGroup.getGroupId()) {
Group layoutGroup = GroupLocalServiceUtil.getGroup(layoutGroupId);
UnicodeProperties typeSettingsProperties =
layoutGroup.getTypeSettingsProperties();
boolean mergeGuestPublicPages = GetterUtil.getBoolean(
typeSettingsProperties.getProperty("mergeGuestPublicPages"));
if (!mergeGuestPublicPages) {
return layouts;
}
List<Layout> guestLayouts = LayoutLocalServiceUtil.getLayouts(
guestGroup.getGroupId(), false,
LayoutConstants.DEFAULT_PARENT_LAYOUT_ID);
Object[] viewableLayouts = getViewableLayouts(
request, user, permissionChecker, layout, guestLayouts);
guestLayouts = (List<Layout>)viewableLayouts[1];
if (layouts == null) {
return guestLayouts;
}
layouts.addAll(0, guestLayouts);
}
else {
HttpSession session = request.getSession();
Long previousGroupId = (Long)session.getAttribute(
WebKeys.VISITED_GROUP_ID_PREVIOUS);
if ((previousGroupId != null) &&
(previousGroupId.longValue() != layoutGroupId)) {
Group previousGroup = null;
try {
previousGroup = GroupLocalServiceUtil.getGroup(
previousGroupId.longValue());
}
catch (NoSuchGroupException nsge) {
if (_log.isWarnEnabled()) {
_log.warn(nsge);
}
return layouts;
}
UnicodeProperties typeSettingsProperties =
previousGroup.getTypeSettingsProperties();
boolean mergeGuestPublicPages = GetterUtil.getBoolean(
typeSettingsProperties.getProperty(
"mergeGuestPublicPages"));
if (!mergeGuestPublicPages) {
return layouts;
}
List<Layout> previousLayouts =
LayoutLocalServiceUtil.getLayouts(
previousGroupId.longValue(), false,
LayoutConstants.DEFAULT_PARENT_LAYOUT_ID);
Object[] viewableLayouts = getViewableLayouts(
request, user, permissionChecker, layout, previousLayouts);
previousLayouts = (List<Layout>)viewableLayouts[1];
if (previousLayouts != null) {
layouts.addAll(previousLayouts);
}
}
}
return layouts;
}
protected void rememberVisitedGroupIds(
HttpServletRequest request, long currentGroupId) {
String requestURI = GetterUtil.getString(request.getRequestURI());
if (!requestURI.endsWith(_PATH_PORTAL_LAYOUT)) {
return;
}
HttpSession session = request.getSession();
Long recentGroupId = (Long)session.getAttribute(
WebKeys.VISITED_GROUP_ID_RECENT);
Long previousGroupId = (Long)session.getAttribute(
WebKeys.VISITED_GROUP_ID_PREVIOUS);
if (recentGroupId == null) {
recentGroupId = new Long(currentGroupId);
session.setAttribute(
WebKeys.VISITED_GROUP_ID_RECENT, recentGroupId);
}
else if (recentGroupId.longValue() != currentGroupId) {
previousGroupId = new Long(recentGroupId.longValue());
recentGroupId = new Long(currentGroupId);
session.setAttribute(
WebKeys.VISITED_GROUP_ID_RECENT, recentGroupId);
session.setAttribute(
WebKeys.VISITED_GROUP_ID_PREVIOUS, previousGroupId);
}
if (_log.isDebugEnabled()) {
_log.debug("Current group id " + currentGroupId);
_log.debug("Recent group id " + recentGroupId);
_log.debug("Previous group id " + previousGroupId);
}
}
protected void servicePre(
HttpServletRequest request, HttpServletResponse response)
throws Exception {
System.out.println("In ServicePreAction-Mobile class-servicePre method");
ThemeDisplay themeDisplay = initThemeDisplay(request, response);
if (themeDisplay == null) {
return;
}
request.setAttribute(WebKeys.THEME_DISPLAY, themeDisplay);
// Service context
ServiceContext serviceContext = ServiceContextFactory.getInstance(
request);
ServiceContextThreadLocal.pushServiceContext(serviceContext);
// Parallel render
boolean parallelRenderEnable = true;
Layout layout = themeDisplay.getLayout();
if (layout != null) {
LayoutTypePortlet layoutTypePortlet =
themeDisplay.getLayoutTypePortlet();
List<String> portletIds = layoutTypePortlet.getPortletIds();
if (portletIds.size() == 1) {
String portletId = portletIds.get(0);
Portlet portlet = PortletLocalServiceUtil.getPortletById(
portletId);
if ((portlet != null) && !portlet.isAjaxable()) {
parallelRenderEnable = false;
}
}
}
Boolean parallelRenderEnableObj = Boolean.valueOf(ParamUtil.getBoolean(
request, "p_p_parallel", parallelRenderEnable));
request.setAttribute(
WebKeys.PORTLET_PARALLEL_RENDER, parallelRenderEnableObj);
// Main Journal article
long mainJournalArticleId = ParamUtil.getLong(request, "p_j_a_id");
if (mainJournalArticleId > 0) {
try{
JournalArticle mainJournalArticle =
JournalArticleServiceUtil.getArticle(mainJournalArticleId);
AssetEntry layoutAssetEntry =
AssetEntryLocalServiceUtil.getEntry(
JournalArticle.class.getName(),
mainJournalArticle.getResourcePrimKey());
request.setAttribute(
WebKeys.LAYOUT_ASSET_ENTRY, layoutAssetEntry);
}
catch (NoSuchArticleException nsae) {
if (_log.isWarnEnabled()) {
_log.warn(nsae.getMessage());
}
}
}
}
protected void updateUserLayouts(User user) throws Exception {
Boolean hasPowerUserRole = null;
// Private layouts
boolean addDefaultUserPrivateLayouts = false;
if (PropsValues.LAYOUT_USER_PRIVATE_LAYOUTS_ENABLED &&
PropsValues.LAYOUT_USER_PRIVATE_LAYOUTS_AUTO_CREATE) {
addDefaultUserPrivateLayouts = true;
if (PropsValues.LAYOUT_USER_PRIVATE_LAYOUTS_POWER_USER_REQUIRED) {
if (hasPowerUserRole == null) {
hasPowerUserRole = hasPowerUserRole(user);
}
if (!hasPowerUserRole.booleanValue()) {
addDefaultUserPrivateLayouts = false;
}
}
}
Boolean hasPrivateLayouts = null;
if (addDefaultUserPrivateLayouts) {
hasPrivateLayouts = LayoutLocalServiceUtil.hasLayouts(user, true);
if (!hasPrivateLayouts) {
addDefaultUserPrivateLayouts(user);
}
}
boolean deleteDefaultUserPrivateLayouts = false;
if (!PropsValues.LAYOUT_USER_PRIVATE_LAYOUTS_ENABLED) {
deleteDefaultUserPrivateLayouts = true;
}
else if (PropsValues.LAYOUT_USER_PRIVATE_LAYOUTS_POWER_USER_REQUIRED) {
if (hasPowerUserRole == null) {
hasPowerUserRole = hasPowerUserRole(user);
}
if (!hasPowerUserRole.booleanValue()) {
deleteDefaultUserPrivateLayouts = true;
}
}
if (deleteDefaultUserPrivateLayouts) {
if (hasPrivateLayouts == null) {
hasPrivateLayouts = LayoutLocalServiceUtil.hasLayouts(
user, true);
}
if (hasPrivateLayouts) {
deleteDefaultUserPrivateLayouts(user);
}
}
// Public pages
boolean addDefaultUserPublicLayouts = false;
if (PropsValues.LAYOUT_USER_PUBLIC_LAYOUTS_ENABLED &&
PropsValues.LAYOUT_USER_PUBLIC_LAYOUTS_AUTO_CREATE) {
addDefaultUserPublicLayouts = true;
if (PropsValues.LAYOUT_USER_PUBLIC_LAYOUTS_POWER_USER_REQUIRED) {
if (hasPowerUserRole == null) {
hasPowerUserRole = hasPowerUserRole(user);
}
if (!hasPowerUserRole.booleanValue()) {
addDefaultUserPublicLayouts = false;
}
}
}
Boolean hasPublicLayouts = null;
if (addDefaultUserPublicLayouts) {
hasPublicLayouts = LayoutLocalServiceUtil.hasLayouts(user, false);
if (!hasPublicLayouts) {
addDefaultUserPublicLayouts(user);
}
}
boolean deleteDefaultUserPublicLayouts = false;
if (!PropsValues.LAYOUT_USER_PUBLIC_LAYOUTS_ENABLED) {
deleteDefaultUserPublicLayouts = true;
}
else if (PropsValues.LAYOUT_USER_PUBLIC_LAYOUTS_POWER_USER_REQUIRED) {
if (hasPowerUserRole == null) {
hasPowerUserRole = hasPowerUserRole(user);
}
if (!hasPowerUserRole.booleanValue()) {
deleteDefaultUserPublicLayouts = true;
}
}
if (deleteDefaultUserPublicLayouts) {
if (hasPublicLayouts == null) {
hasPublicLayouts = LayoutLocalServiceUtil.hasLayouts(
user, false);
}
if (hasPublicLayouts) {
deleteDefaultUserPublicLayouts(user);
}
}
}
protected File privateLARFile;
protected File publicLARFile;
private static final String _CONTROL_PANEL_CATEGORY_PORTLET_PREFIX =
"portlet_";
private static final String _PATH_PORTAL_LAYOUT = "/portal/layout";
private static Log _log = LogFactoryUtil.getLog(ServicePreAction.class);
}
overriding servicePreAction class using hooks in liferay
DesTincT/Content disappear in IE6/Maxthon with expressions ( CSS)
/* style.css
-------------*/
#container {
position:relative; /* remove this */
min-width:999px;
max-width:1140px;
margin:0px auto 0px auto;
z-index:1;
}
/* ie6.css
-------------*/
#container {
position:static; /* or you can add this only to ie */
width:expression((document.documentElement.clientWidth || document.body.clientWidth) <= 1001? "999px" :
(document.documentElement.clientWidth || document.body.clientWidth) >= 1142? "1140px" : "auto");
}
Content may disappear on window resize in IE6/Maxthon, when using expressions to set min-width/max-width. To fix it - just remove 'position:relative' in #container.
zensir/Accessible CSS Forms: Using CSS to Create a Two-Column Layout ( CSS)
<style type="text/css">
<!--
form { /* set width in form, not fieldset (still takes up more room w/ fieldset width */
font:100% verdana,arial,sans-serif;
margin: 0;
padding: 0;
min-width: 500px;
max-width: 600px;
width: 560px;
}
form fieldset {
/ * clear: both; note that this clear causes inputs to break to left in ie5.x mac, commented out */
border-color: #000;
border-width: 1px;
border-style: solid;
padding: 10px; /* padding in fieldset support spotty in IE */
margin: 0;
}
form fieldset legend {
font-size:1.1em; /* bump up legend font size, not too large or it'll overwrite border on left */
/* be careful with padding, it'll shift the nice offset on top of border */
}
form label {
display: block; /* block float the labels to left column, set a width */
float: left;
width: 150px;
padding: 0;
margin: 5px 0 0; /* set top margin same as form input - textarea etc. elements */
text-align: right;
}
form fieldset label:first-letter { /* use first-letter pseudo-class to underline accesskey, note that */
text-decoration:underline; /* Firefox 1.07 WIN and Explorer 5.2 Mac don't support first-letter */
/* pseudo-class on legend elements, but do support it on label elements */
/* we instead underline first letter on each label element and accesskey */
/* each input. doing only legends would lessens cognitive load */
/* opera breaks after first letter underlined legends but not labels */
}
form input, form textarea {
/* display: inline; inline display must not be set or will hide submit buttons in IE 5x mac */
width:auto; /* set width of form elements to auto-size, otherwise watch for wrap on resize */
margin:5px 0 0 10px; /* set margin on left of form elements rather than right of
label aligns textarea better in IE */
}
form input#reset {
margin-left:0px; /* set margin-left back to zero on reset button (set above) */
}
textarea { overflow: auto; }
form small {
display: block;
margin: 0 0 5px 160px; /* instructions/comments left margin set to align w/ right column inputs */
padding: 1px 3px;
font-size: 88%;
}
form .required{font-weight:bold;} /* uses class instead of div, more efficient */
form br {
clear:left; /* setting clear on inputs didn't work consistently, so brs added for degrade */
}
-->
</style>
<script>
<!--
function sf(){document.f.firstname.focus();}
-->
</script>
</head>
<body onLoad=sf()>
<form action="#" method="post" name="f">
<p><b>Bold</b> fields are required. <u>U</u>nderlined letters are accesskeys.</p>
<fieldset>
<legend>Personal Information</legend>
<label for="firstname" accesskey="f">First name: </label>
<input type="text" id="firstname" name="firstname" tabindex="1" value="" title="first name"><br>
<label for="lastname" accesskey="l">Last name: </label>
<input type="text" id="lastname" name="lastname" tabindex="2" title="last name"><br>
<label for="email" class="required" accesskey="e">Email: </label>
<input type="text" id="email" name="email" tabindex="3" title="email"><br>
<small>Your email address is safe with us, until we're acquired.</small>
</fieldset>
<fieldset>
<legend>Comments</legend>
<label for="comments" accesskey="c">Comments: </label>
<textarea name="comments" rows="3" cols="23" id="comments" tabindex="4" title="comments"></textarea><br>
<label for="kludge"></label>
<input type="submit" value="Send" id="submit" tabindex="5"> <INPUT type="reset" id="reset" tabindex="6">
</fieldset>
</form>
In a recent study of web design patterns, Dr. Melody Ivory found that accessibility is the most underutilized aspect of good web page design (Ivory 2005). In fact websites have become more complex and less accessible over time (Hackett 2003). Less than 20% of the Fortune 100 have websites that are fully accessible (Loiacono 2004). Accessible forms are one way to combat this disturbing trend. With CSS layout, you can create two-column forms without the use of tables to save space and time. This article shows how to create a simple two-column contact form using CSS to style structural elements that is both fast and accessible.
A survey of CSS-based forms revealed many variations on a theme (see Vandersluis 2004). Most use block-level floats and margins to position form elements on the page. However, in my testing I found IE5.x Mac to have rendering problems with many of these forms. After numerous iterations, I arrived at a solution that worked for IE5.x Mac as well as Safari 1.07 Mac, Firefox 1.07 Win/Mac, IE 6 Win, Camino, and Opera. Our goal here is to create a simple accessible contact form without the use of tables (see Figure 1).
Abiotic/CSS Footer ( CSS)
html, body, #contents {
min-height: 100%;
width: 100%;
height: 100%;
}
/*
* The "height" above is a hack for IE5+/Win. Below we adjust
* it using the child selector to hide from IE5+/Win
*/
html>body, html>body #contents {
height: auto;
}
/*
* Without this, Moz1.0 adds a vertical scrollbar
*/
body {
margin: 0;
font-family: Arial, sans-serif;
}
#contents {
position: absolute;
top: 0;
left: 0;
/* Use the following to center this at 50% width, or this for 750px: width: 700px, margin-left: -350px: */
/*
left: 50%;
width: 50%;
margin-left: -25%;
*/
}
#footer {
position: absolute;
bottom: 0;
background-color: #ccffcc;
width: 70%; /* See note below */
text-align: center;
padding: 0 15%;
}
/* SBMH -- see http://css-discuss.incutio.com/?page=BoxModelHack
* Stupid hack lets IE see 100%, others see 70%.
*/
#footer {
\width: 100%;
w\idth: 70%;
}
#main {
margin-bottom: 5em;
height: auto;
padding: .5em;
}
This demonstrates one approach to the problem of placing a footer in a position described by Tuttle Grey as follows:
- render an element at the bottom of the canvas, except...
- when the page content is shorter than the viewport, render that element at the bottom of the viewport.
See posting to css-discuss
This page should be small enough to demonstrate the second point. For a demo of the first point using the same style, see FooterDemo2. The stylesheet can be found at FooterDemo.css. This has been tested and works in IE5.5+/Win, Moz0.9.9, and Moz1.0. It does not work in Opera 6. Any suggestions for that would be appreciated.