aboutsummaryrefslogtreecommitdiffstats
path: root/src/com/itmill/toolkit/terminal/web/ThemeFunctionLibrary.java
blob: 88029e05d444d0d470b6359b56554a864b7120d9 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
/* *************************************************************************
 
 IT Mill Toolkit 

 Development of Browser User Interfaces Made Easy

 Copyright (C) 2000-2006 IT Mill Ltd
 
 *************************************************************************

 This product is distributed under commercial license that can be found
 from the product package on license.pdf. Use of this product might 
 require purchasing a commercial license from IT Mill Ltd. For guidelines 
 on usage, see licensing-guidelines.html

 *************************************************************************
 
 For more information, contact:
 
 IT Mill Ltd                           phone: +358 2 4802 7180
 Ruukinkatu 2-4                        fax:   +358 2 4802 7181
 20540, Turku                          email:  info@itmill.com
 Finland                               company www: www.itmill.com
 
 Primary source for information and releases: www.itmill.com

 ********************************************************************** */

package com.itmill.toolkit.terminal.web;

import com.itmill.toolkit.Application;
import com.itmill.toolkit.terminal.ThemeResource;
import com.itmill.toolkit.ui.FrameWindow;
import com.itmill.toolkit.ui.Window;

import java.text.DateFormatSymbols;
import java.util.Calendar;
import java.util.Collection;
import java.util.GregorianCalendar;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Set;

import javax.servlet.http.HttpSession;

/**
 * This a function library that can be used from the theme XSL-files. It
 * provides easy access to current application, window, theme, webbrowser and
 * session. The internal threadlocal state must be maintained by the webadapter
 * in order go guarantee that it works.
 * 
 * @author IT Mill Ltd.
 * @version
 * @VERSION@
 * @since 3.0
 */

public class ThemeFunctionLibrary {

	static private final int APPLICATION = 0;

	static private final int WINDOW = 1;

	static private final int WEBBROWSER = 2;

	static private final int SESSION = 3;

	static private final int WEBADAPTERSERVLET = 4;

	static private final int THEME = 5;

	static private ThreadLocal state = new ThreadLocal();

	static protected void setState(Application application, Window window,
			WebBrowser webBrowser, HttpSession session,
			ApplicationServlet webAdapterServlet, String theme) {
		state.set(new Object[] { application, window, webBrowser, session,
				webAdapterServlet, theme });
	}

	static protected void cleanState() {
		state.set(null);
	}

	/**
	 * Returns a reference to the application object associated with the session
	 * that the call came from.
	 */
	static public Application application() {
		try {
			return (Application) ((Object[]) state.get())[APPLICATION];
		} catch (NullPointerException e) {
			throw new IllegalStateException();
		}
	}

	/**
	 * Returns a reference to the current window object associated with the
	 * session that the call came from.
	 */
	static public Window window() {
		try {
			return (Window) ((Object[]) state.get())[WINDOW];
		} catch (NullPointerException e) {
			throw new IllegalStateException();
		}
	}

	/**
	 * Returns a reference to the browser object associated with the session
	 * that the call came from.
	 */
	static public WebBrowser browser() {
		try {
			return (WebBrowser) ((Object[]) state.get())[WEBBROWSER];
		} catch (NullPointerException e) {
			throw new IllegalStateException();
		}
	}

	/**
	 * Returns a reference to the current servlet http session object that is
	 * associated with the session that the call came from.
	 */
	static public HttpSession session() {
		try {
			return (HttpSession) ((Object[]) state.get())[SESSION];
		} catch (NullPointerException e) {
			throw new IllegalStateException();
		}
	}

	/**
	 * Return a reference to the current theme name that is associated with the
	 * session that the call came from.
	 */
	static public String theme() {
		try {
			return (String) ((Object[]) state.get())[THEME];
		} catch (NullPointerException e) {
			throw new IllegalStateException();
		}
	}

	/**
	 * Return an URI to the named resource from the named theme.
	 */
	static public String resource(String resource, String theme) {
		try {
			return ((ApplicationServlet) ((Object[]) state.get())[WEBADAPTERSERVLET])
					.getResourceLocation(theme, new ThemeResource(resource));
		} catch (NullPointerException e) {
			throw new IllegalStateException();
		}
	}

	/**
	 * Return an URI to the named resource.
	 */
	static public String resource(String resource) {
		try {
			return ((ApplicationServlet) ((Object[]) state.get())[WEBADAPTERSERVLET])
					.getResourceLocation(theme(), new ThemeResource(resource));
		} catch (NullPointerException e) {
			throw new IllegalStateException();
		}
	}

	/**
	 * Generate JavaScript for page that performs client-side combility checks.
	 */
	static public boolean probeClient() {
		return (browser().performClientCheck() && !browser()
				.isClientSideChecked());
	}

	/**
	 * Generate JavaScript for page header that handles window refreshing,
	 * opening and closing.
	 * 
	 * Generates script that:
	 * <ul>
	 * <li>Requests that all windows that need repaint be reloaded</li>
	 * <li>Sets the window name</li>
	 * <li>Closes window if it is set to be closed </li>
	 * <ul>
	 * 
	 */
	static public String windowScript() {
		return generateWindowScript(
				window(),
				application(),
				(ApplicationServlet) ((Object[]) state.get())[WEBADAPTERSERVLET],
				browser());
	}

	static protected String generateWindowScript(Window window,
			Application app, ApplicationServlet wa, WebBrowser browser) {

		StringBuffer script = new StringBuffer();
		LinkedList update = new LinkedList();

		// Add all the windows needto update list
		Set dirtyWindows = wa != null ? wa.getDirtyWindows(app) : null;
		if (dirtyWindows != null)
			for (Iterator i = dirtyWindows.iterator(); i.hasNext();) {
				Window w = (Window) i.next();
				if (w != window) {
					if (w instanceof FrameWindow)
						update.addFirst(w);
					else
						update.addLast(w);
				}
			}

		// Remove all windows that are in frames, of such frame windows that
		// will be updated anyway
		Object[] u = update.toArray();
		if (u.length > 0 && (window != null && window instanceof FrameWindow))
			u[u.length - 1] = window;
		for (int i = 0; i < u.length; i++) {
			try {
				FrameWindow w = (FrameWindow) u[i];
				LinkedList framesets = new LinkedList();
				framesets.add(w.getFrameset());
				while (!framesets.isEmpty()) {
					FrameWindow.Frameset fs = (FrameWindow.Frameset) framesets
							.removeFirst();
					for (Iterator j = fs.getFrames().iterator(); j.hasNext();) {
						FrameWindow.Frame f = (FrameWindow.Frame) j.next();
						if (f instanceof FrameWindow.Frameset)
							framesets.add(f);
						else if (f.getWindow() != null) {
							update.remove(f.getWindow());
							wa.removeDirtyWindow(app, f.getWindow());
						}
					}
				}
			} catch (ClassCastException ignored) {
			}
		}

		// Set window name
		if (window != null) {
			script.append("window.name = \"" + getWindowTargetName(app, window)
					+ "\";\n");
		}

		// Generate window updatescript
		for (Iterator i = update.iterator(); i.hasNext();) {
			Window w = (Window) i.next();
			script.append(getWindowRefreshScript(app, w, browser));

			wa.removeDirtyWindow(app, w);

			// Windows that are closed immediately are "painted" now
			if (w.getApplication() == null || !w.isVisible())
				w.requestRepaintRequests();
		}

		// Close current window if it is not visible
		if (window == null || !window.isVisible())
			script.append("window.close();\n");

		return script.toString();
	}

	/**
	 * Returns an unique target name for a given window name.
	 * 
	 * @param windowName
	 *            Name of the window.
	 * @return An unique ID for window target
	 * @throws IllegalStateException
	 *             If application for window is null.
	 */
	static public String getWindowTargetName(Application application,
			Window window) {
		try {
			return "" + application.hashCode() + "_" + window.getName();
		} catch (NullPointerException e) {
			throw new IllegalStateException();
		}
	}

	/**
	 * Returns an unique target name for current window.
	 * 
	 * @return An unique ID for window target
	 */
	static public String getWindowTargetName() {
		return getWindowTargetName(application(), window());
	}

	/**
	 * Returns an unique target name for current window.
	 * 
	 * @return An unique ID for window target
	 * @throws IllegalStateException
	 *             If application for window is null.
	 */
	static public String getWindowTargetName(String name) {
		Window w = application().getWindow(name);
		if (w != null)
			return getWindowTargetName(application(), w);
		else
			return name;
	}

	/* Static mapping for 0 to be sunday. */
	private static int[] weekdays = new int[] { Calendar.SUNDAY,
			Calendar.MONDAY, Calendar.TUESDAY, Calendar.WEDNESDAY,
			Calendar.THURSDAY, Calendar.FRIDAY, Calendar.SATURDAY };

	/**
	 * Returns the country and region code for current application locale.
	 * 
	 * @see Locale#getCountry()
	 * @return language Country code of the current application locale.
	 */
	static public String getLocaleCountryId() {
		try {
			Application app = (Application) ((Object[]) state.get())[APPLICATION];
			return app.getLocale().getCountry();
		} catch (NullPointerException e) {
			throw new IllegalStateException();
		}
	}

	/**
	 * Returns the language code for current application locale.
	 * 
	 * @see Locale#getLanguage()
	 * @return language Language code for current application locale.
	 */
	static public String getLocaleLanguageId() {
		try {
			Application app = (Application) ((Object[]) state.get())[APPLICATION];
			return app.getLocale().getLanguage();
		} catch (NullPointerException e) {
			throw new IllegalStateException();
		}
	}

	/**
	 * Get name for week day.
	 * 
	 * @param Number
	 *            of week day. 0 first day of week.
	 * @return Name of week day in applications current locale.
	 */
	static public int getFirstDayOfWeek() {
		try {
			Application app = (Application) ((Object[]) state.get())[APPLICATION];
			Calendar cal = new GregorianCalendar(app.getLocale());
			int first = cal.getFirstDayOfWeek();
			for (int i = 0; i < 7; i++) {
				if (first == weekdays[i])
					return i;
			}
			return 0; // default to sunday
		} catch (NullPointerException e) {
			throw new IllegalStateException();
		}
	}

	/**
	 * Get name for week day.
	 * 
	 * @param Number
	 *            of week day. 0 sunday, 1 monday, ...
	 * @return Name of week day in applications current locale.
	 */
	static public String getShortWeekday(int dayOfWeek) {
		try {
			Application app = (Application) ((Object[]) state.get())[APPLICATION];
			DateFormatSymbols df = new DateFormatSymbols(app.getLocale());
			return df.getShortWeekdays()[weekdays[dayOfWeek]];
		} catch (NullPointerException e) {
			throw new IllegalStateException();
		}
	}

	/**
	 * Get short name for month.
	 * 
	 * @param Number
	 *            of month. 0 is January, 1 is February, and so on.
	 * @return Name of month in applications current locale.
	 */
	static public String getShortMonth(int month) {
		try {
			Application app = (Application) ((Object[]) state.get())[APPLICATION];
			DateFormatSymbols df = new DateFormatSymbols(app.getLocale());
			String monthName = df.getShortMonths()[month];
			return monthName;
		} catch (NullPointerException e) {
			throw new IllegalStateException();
		}
	}

	/**
	 * Get name for month.
	 * 
	 * @param Number
	 *            of month. 0 is January, 1 is February, and so on.
	 * @return Name of month in applications current locale.
	 */
	static public String getMonth(int month) {
		try {
			Application app = (Application) ((Object[]) state.get())[APPLICATION];
			DateFormatSymbols df = new DateFormatSymbols(app.getLocale());
			String monthName = df.getMonths()[month];
			return monthName;
		} catch (NullPointerException e) {
			throw new IllegalStateException();
		}
	}

	/**
	 * Get Form Action URL for the requested window.
	 * 
	 * <p>
	 * This returns the action for the window main form. This action can be set
	 * through WebApplicationContect setWindowFormAction method..
	 * </p>
	 * 
	 * @return Form action for the current window.
	 */
	static public String getFormAction() {

		Window win = window();
		Application app = application();

		return ((WebApplicationContext) app.getContext())
				.getWindowFormAction(win);
	}

	/** Generate links for CSS files to be included in html head. */
	static public String getCssLinksForHead() {
		ApplicationServlet as = (ApplicationServlet) ((Object[]) state.get())[WEBADAPTERSERVLET];
		Theme t = as.getThemeSource().getThemeByName(theme());
		Collection allFiles = t.getFileNames(browser(), Theme.MODE_HTML);
		StringBuffer links = new StringBuffer();
		for (Iterator i = allFiles.iterator(); i.hasNext();) {
			String file = (String) i.next();
			if (file.endsWith(".css")) {
				links
						.append("<LINK REL=\"STYLESHEET\" TYPE=\"text/css\" HREF=\""
								+ resource(file) + "\"/>\n");
			}
		}
		return links.toString();
	}

	/** Generate links for JavaScript files to be included in html head. */
	static public String getJavaScriptLinksForHead() {
		ApplicationServlet as = (ApplicationServlet) ((Object[]) state.get())[WEBADAPTERSERVLET];
		Theme t = as.getThemeSource().getThemeByName(theme());
		Collection allFiles = t.getFileNames(browser(), Theme.MODE_HTML);
		StringBuffer links = new StringBuffer();
		for (Iterator i = allFiles.iterator(); i.hasNext();) {
			String file = (String) i.next();
			if (file.endsWith(".js")) {
				links.append("<SCRIPT LANGUAGE=\"Javascript\" SRC=\""
						+ resource(file) + "\"></SCRIPT>\n");
			}
		}
		return links.toString();
	}

	/** Generate JavaScript for updating given window */
	static protected String getWindowRefreshScript(Application application,
			Window window, WebBrowser browser) {

		if (application == null)
			return "";

		if (window == null)
			return "";

		if (window == null)
			return "";

		// If window is closed or hidden
		if (window.getApplication() == null || !window.isVisible())
			return "win = window.open(\"\",\""
					+ getWindowTargetName(application, window) + "\");\n  "
					+ "if (win != null) { win.close(); }\n";

		String url = window.getURL().toString();

		String features = "dependent=yes,";
		int width = window.getWidth();
		int height = window.getHeight();
		if (width >= 0)
			features += "width=" + width;
		if (height >= 0)
			features += ((features.length() > 0) ? "," : "") + "height="
					+ height;
		switch (window.getBorder()) {
		case Window.BORDER_NONE:
			features += ((features.length() > 0) ? "," : "")
					+ "toolbar=0,location=0,menubar=0,status=0,resizable=1,scrollbars="
					+ (window.isScrollable() ? "1" : "0");
			break;
		case Window.BORDER_MINIMAL:
			features += ((features.length() > 0) ? "," : "")
					+ "toolbar=1,location=0,menubar=0,status=1,resizable=1,scrollbars="
					+ (window.isScrollable() ? "1" : "0");
			break;
		case Window.BORDER_DEFAULT:
			features += ((features.length() > 0) ? "," : "")
					+ "toolbar=1,location=1,menubar=1,status=1,resizable=1,scrollbars="
					+ (window.isScrollable() ? "1" : "0");
			break;
		}

		String script = "win = window.open(\"\",\""
				+ getWindowTargetName(application, window) + "\",\"" + features
				+ "\");\n" + "if (win != null) {" + "var form = null;";

		if (browser != null
				&& (browser.getJavaScriptVersion().supports(
						WebBrowser.JAVASCRIPT_1_5) || browser
						.getJavaScriptVersion()
						.supports(WebBrowser.JSCRIPT_1_0))) {
			script += "try { form = win.document.forms[\"itmill\"]; if (typeof form != 'undefined') form = win.document.forms[\"millstone\"];"
					+ "} catch (e) { form = null;}";
		} else {
			script += "form = win.document.forms[\"itmill\"]; if (typeof form != 'undefined') form = win.document.forms[\"millstone\"];";
		}

		script += "if (form != null) {" + "form.submit();"
				+ "} else {win.location.href = \"" + url + "\";}}";

		return script;
	}
}