~ubuntu-tour/+junk/new-lang-system

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
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
#!/usr/bin/env python

import glob
import os
import re
import locale
import gtk
import pygtk
from translate import Translate


class T:
	
	#When the class is loaded
	def __init__(self, tour, directory):

		#Folder
		self.folder = directory
		
		#Parent tour class
		self.tour = tour
		
		#Some empty values to fill later
		self.lang, self.info, self.parent, self.name, self.pos, self.default, self.id, self.t_pages = None, None, None, None, None, None, None, None
		
		#Run some stuff
		self.detect_lang()
		self.get_tour_info()
		self.num_pages()
	
	
	#Def detect lang
	def detect_lang(self):
		
		#Try using the language and country
		if os.path.isdir(os.path.join(self.folder, self.tour.user_lang)):
			self.lang = self.tour.user_lang
		
		#Fallback on just the language
		elif os.path.isdir(os.path.join(self.folder, self.tour.user_lang.split('_')[0])):
			self.lang = self.tour.user_lang.split('_')[0]
		
		#Fallback on default language
		else:
			self.lang = self.tour.default_lang
		
		#And return
		return self.lang
	
	
	#Get the tour info
	def get_tour_info(self):
		
		#Try and open the file
		try:
			#Load the info
			info = open(os.path.join(self.folder, self.lang, 'tour.info'),'r').read()
			
			#Parse the info
			self.info = {}
			for line in info.split('\n'):
				if ':' in line:
					l = line.split(':')
					self.info[l[0]] = l[1]
			
			#This is deliberately bad coding, so that if the tour is invalid, it will break the try and force the except to work.
			self.parent = self.info['parent']
			self.name = self.info['name']
			try:
				self.pos = int(self.info['position'])
			except:
				self.pos = 1000
			try:
				self.default = int(self.info['default'])#TODO: impliment features using this.
			except:
				self.default = 0
			
			#If it survived that it's valid.
			self.is_valid = True
		
		#Tour is not valid.
		except:
			self.tour.p(self.folder + " does not have a tour.info, folder rejected.")
			self.is_valid = False
	
	
	#How many pages
	def num_pages(self):
		
		#Get all the pages
		pages = glob.glob(os.path.join(self.folder, self.lang, "*"))
		
		#Loop through the pages
		count = 0
		for p in pages:
			if '_' in p.split('/')[-1]:
				try:
					page = int(p.split('/')[-1].split('_')[0])
					if page > count:
						count = page
				except:
					self.tour.p('Warning, ' + p.split('/')[-1] + ' contains an underscore, please rename.')
		
		#Set
		self.t_pages = count
		
		#How many then?
		return self.t_pages
	
	
	#Set id
	def set_id(self, n):
		self.id = n


class Tour:

	#Things to do when class is loaded
	def __init__(self, debug, html, colours):
		self.default_lang = 'en'
		self.user_lang = self.detect_lang()
		self.dialect = self.load_dialect()
		
		self.debug = debug
		self.html = html
		self.colours = colours
		self.parse_colours()
		
		self.folder=None
		self.page=0
		self.t_pages = 0
		
		self.progression_reqs = ''
		self.fullscreen = False
		
		self.get_sections()
		
		self.catagories = ['Hidden', 'Getting Started', 'Internet', 'Office', 'Multimedia', 'Continue Playing']
	
	#Debug print function
	def p(self, string):
		if self.debug:
			print string


	#Get a list of tutorials available
	def get_sections(self):
		#Get all for folders
		if os.path.exists(os.path.join(os.getcwd(), "tours")):
			dirs = glob.glob(os.path.join(os.getcwd(), "tours", "*"))
		elif os.path.exists(os.path.join("/", "usr","share","ubuntu-tour","tours")):
			dirs = glob.glob(os.path.join("/", "usr","share","ubuntu-tour","tours","*"))
		elif os.path.exists(os.path.join(os.path.expanduser('~'), ".ubuntu-tour", "tours")):
			dirs = glob.glob(os.path.join(os.path.expanduser('~'), ".ubuntu-tour", "tours", "*"))
		
		#Go through the folders
		self.tours = []
		n = 0
		for folder in dirs:
			tour = T(self, folder)
			if tour.is_valid:
				tour.set_id(n)
				self.tours.append(tour)
				n+=1
				
		#Return the list
		return self.tours


		def GetDefaultApp(Type):
			if (Type.lower() == "browser"):
				return os.popen("gconftool-2 -g /desktop/gnome/applications/browser/exec").read()[:-1]
			elif (Type.lower() == "music" or Type.lower() == "media"):
				return os.popen("gconftool-2 -g /desktop/gnome/applications/media/exec").read()[:-1]
			else:
				print "There's no support for looking up the apps for \"" + Type + "\""
			return 0

	#Load page
	def load_page(self, tour_id, page=0, fullscreen=False, dark=False):
		#Debug
		self.p("Loading page")
		
		#Get the folder name and page number
		self.page = int(page)
		
		#Get the tour
		self.current_tour = self.tours[int(tour_id)]
		tour = self.current_tour
		
		#Try and read the page, if not, return a generic page
		try:
			#Get the files
			files = glob.glob(tour.folder + "/" + tour.lang + '/' + str(self.page) + "_*")
			
			#Find the html one
			html = -1
			for n in range(0, len(files)):
				if files[n].split('.')[-1] == 'html':
					html = n
			
			#Are we using the html
			if self.html:
			
				#Is there a html file?
				if html >= 0:
					#Open the html file
					msg = open(files[html],'r')
					
					#Get the text
					text = msg.read()
				
				else:
					#Open the text file
					msg = open(files[html],'r')
					
					#Get the text
					text = msg.read()
					
					#Convert to html
					text = self.raw_to_html(text)
			
			#Otherwise we are using plain text
			else:
				#Usually the file will be 0
				f = 0
				convert = False
				
				#If however -1 is the html
				if html == -1:
					#If there is another file
					if len(files) > 1:
						f = 1
					
					#Otherwise convert the html file to a text file
					else:
						convert = True
				
				#Open the file
				msg=open(files[f],'r')
			
				#Get the text
				text = msg.read()
				
				#Should we try and convert
				if convert:
					text = self.html_to_raw(text)
			
			#Get the progression requirements
			if '"Requirements" -->' in text:
				reqs = text.split('"Requirements" -->', 2)[0]
				if '<!-- "Requirements"' in reqs:
					reqs = reqs.split('<!-- "Requirements"', 2)[1]
					
					#Save these requirements
					self.progression_reqs = reqs
				
				else:
					self.progression_reqs = ''

			else:
				self.progression_reqs = ''
					
			#Convert text to the local dialect
			if not '_' in tour.lang:
				self.p('using dialect')
				text = self.convert_to_dialect(text)	
			
			#Set the text
			if self.html:
				self.gui.html.load_html_string(self.parse_html(text, dark), 'file://' + tour.folder + "/" + tour.lang + "/")
			else:
				self.gui.buffer.set_text(text)
			
			#Category homes
			if tour.name == "Home":
				if tour.parent == "Hidden":
					self.gui.addressbar.set_items(['Home'])
				else:
					self.gui.addressbar.set_items(['Home', tour.parent])
			
			#General tours
			elif tour.parent != "Hidden":
				self.gui.addressbar.set_items(['Home', tour.parent, tour.name])
					
			
			#Close the file
			msg.close()
			
		except:
			#If we can't load the file, we should give some generic text.
			if self.html:
				self.gui.html.load_html_string(self.parse_html("Nothing written yet.", dark), 'file://' + tour.folder + "/" + tour.lang + "/")
			else:
				self.gui.buffer.set_text("Nothing written yet.")
		
		finally:
			
			#Fullscreen?
			if fullscreen:
				if not self.fullscreen:
					#Hide everything
					self.gui.progressbar.hide()
					self.gui.buttonbox.hide()
					self.gui.menuscroll.hide()
					
					#Set to fullscreen
					self.fullscreen = True
					
			else:
				if self.fullscreen:
					#Show everything
					self.gui.progressbar.show()
					self.gui.buttonbox.show()
					self.gui.menuscroll.show()
					
					#Now longer fullscreen
					self.fullscreen = False
		
		#Now we have loaded the page, lets see about the position.
		if tour.t_pages == 0:
			self.gui.next_button.set_sensitive(False)
			self.gui.back_button.set_sensitive(False)
		elif self.page == 0:
			self.gui.next_button.set_sensitive(True)
			self.gui.back_button.set_sensitive(False)
		elif self.page == tour.t_pages:
			self.gui.next_button.set_sensitive(False)
			self.gui.back_button.set_sensitive(True)
		else:
			self.gui.next_button.set_sensitive(True)
			self.gui.back_button.set_sensitive(True)
		
		if self.page==1 and self.current_tour.name=="Managing software":
			self.gui.next_button.hide()
			self.gui.check_button.show()
		else:
			self.gui.next_button.show()
			self.gui.check_button.hide()
		
		#Progress
		if tour.t_pages > 0:
			progress = float(self.page) / float(tour.t_pages)
		else:
			progress = 1
		self.gui.progressbar.set_fraction(progress)
		
	
	
	#How many pages
	def num_pages(self, tutorial):
		#Get the path to the tutorial
		path = os.getcwd() + "/" + tutorial.replace(" ","-").lower() + "/"
		
		#Get all the pages
		pages = glob.glob(path + self.default_lang + "/*")
		
		#Loop through the pages
		count = 0
		for p in pages:
			if '_' in p:
				page = int(p.split('/')[-1].split('_')[0])
				if page > count:
					count = page
		
		#How many then?
		return count


	#Detect the language that the user is using.
	def detect_lang(self):
		#Return the language 
		return locale.getdefaultlocale()[0]
	
	
	#Detect the local dialect
	def load_dialect(self):
		
		#Dialects, start off empty
		dialects = {}
		
		#For all the possible paths
		for path in [os.path.join("/", "usr","share","ubuntu-tour","dialects", self.user_lang), os.path.join(os.getcwd(), "dialects", self.user_lang)]:
		
			#See if the dialect exists here
			if os.path.exists(path):
				#Read
				f = open(path, 'r')
				repls = f.read()
				f.close()
				
				#Loop through replacements
				for replace in repls.split('\n'):
					#Is it valid
					if '->' in replace:
						#Get the find and replace part
						r = replace.split('->', 1)
						
						#And clean then
						r[0] = r[0].strip()
						r[1] = r[1].strip()
						
						#And add to the dialect, provided there is something
						if len(r[0]) > 0:
							dialects[r[0]] = r[1]
		
		#All done, return the dialects
		return dialects
	
	
	#Convert text into the dialect
	def convert_to_dialect(self, text):
		self.p(self.dialect)
		
		#Create a regex search for words which need changing
		regex = '((.|\\r|\\n)(' + '|'.join(self.dialect.keys()) + ')(.|\\r|\\n))'
		
		#Make a note of softkeys to remove
		softkey_remove = []
		softkey = '@'
		
		#Loop through all items of the original language
		for i in re.findall(regex,text):
			#self.p(i)
			#Try and convert it
			try:
				#If it is being used in the html, then we should not change it. (Protection against colo(u)r and cent[re/er])
				if i[2] == 'color' and i[3] == '=':
					replace = i[0]
				if i[2] == 'center' and i[1] == '=':
					replace = i[0]
				
				#If prepended by an softkey symbol, then we don't convert
				elif i[1] == softkey:
					softkey_remove.append(i[2] + i[3])
					replace = i[0]
				
				#Otherwise, we convert
				else:
					replace = i[1] + self.dialect[i[2]] + i[3]
				
				#Go ahead and replace
				if i[0] != replace:
					self.p(i[0] + " to be replaced with " + replace)
					text = text.replace(i[0], replace)
			
			#If something goes wrong, complain quitly
			except Exception, e:
			
				#Error!!
				#TODO: this spams '' errors. Why?
				#self.p(e)
				pass
		
		#Now remove the softkeys
		for s in softkey_remove:
			text = text.replace(softkey + s, s)
		
		#And return the new text
		return text
	
	#Convert a plain text file to html
	def raw_to_html(self, text):
		
		#Convert line breaks
		text = text.replace('\n', '<br />\n')
		
		#Return
		return text
	
	
	#Convert html to plain
	def html_to_raw(self, text):
		
		#Convert line breaks
		text = text.replace('\r', '')
		text = text.replace('\r\n', '\n')
		text = text.replace('<br />\n', '\n')
		text = text.replace('<br />', '\n')
		
		#Return
		return text
	
	
	#Parse html, to get a whole page
	def parse_html(self, html, dark=False):
	
		#For Lightbox Effect: Search for screenshot tag and replace with img tag
		pattern			= r'''<screenshot([^"]+)src="([^"]+)"([^>]+)'''
		pattern_string	= re.compile(pattern)
		replace_string	= r'''<a id="lightbox" href="\2"><img src="\2" \1\3></a'''
		if re.search(pattern_string,html):
			html = re.sub(pattern_string,replace_string,html)

		#Get the html opening
		f = open(os.getcwd() + "/html/start.html",'r')
		start = f.read()
		f.close()
		
		#Get the html closing
		f = open(os.getcwd() + "/html/end.html",'r')
		end = f.read()
		f.close()
		
		#Get full html
		html = start + html + end
		
		#Parse colour
		if dark:
			html = html.replace('{{BACK-COLOUR}}', self.colours['background_t'][0])
			html = html.replace('{{TEXT-COLOUR}}', self.colours['foreground_t'][0])
		else:
			html = html.replace('{{BACK-COLOUR}}', self.colours['background'][0])
			html = html.replace('{{TEXT-COLOUR}}', self.colours['foreground'][0])
		
		#Return the combined html
		return html
	
	
	#Parse the colours
	def parse_colours(self):
		#Loop through them
		for k in self.colours.keys():
			#Get 64k colour hex
			hex = self.colours[k].to_string()
			
			#Convert to 256 colour hex
			if len(hex) == 13:
				hex = hex[0:3] + hex[5:7] + hex[9:11]
			
			#Set the colour
			self.colours[k] = (hex, self.colours[k])
	
	
	#Make the menu
	def make_menu(self, gui):
	
		#Load the gui
		self.gui = gui
		
		#Create a treeview
		self.tree_menu = gtk.TreeView()
		
		#Create a column
		self.tree_sections = gtk.TreeViewColumn("Chapters", gtk.CellRendererText(), text=0)
		self.tree_menu.append_column(self.tree_sections)
		
		self.tree_ids = gtk.TreeViewColumn("ID", gtk.CellRendererText(), text=1)
		self.tree_ids.set_visible(False)
		self.tree_menu.append_column(self.tree_ids)
		
		#Create the store
		self.update_menu()
			
		#Add a callback
		self.tree_menu.get_selection().connect("changed", self.row_selected)
		self.tree_menu.set_property("headers-visible", False)
		
		self.tree_menu.modify_base(gtk.STATE_NORMAL, self.colours['background'][1])
		self.tree_menu.modify_text(gtk.STATE_NORMAL, self.colours['foreground'][1])
		self.tree_menu.expand_all()
		
		#Append, if it's not already there
		child = self.gui.menuscroll.get_child()
		if child == None:
			self.gui.menuscroll.add(self.tree_menu)
		#self.gui.hbox.pack_start(self.tree_menu, False, True)
	
	
	#Make the menu
	def update_menu(self, rescan=True):
		
		#Get the tours
		if rescan:
			self.get_sections()
		
		#Create the store
		self.tree_store = gtk.TreeStore(str, int)
		
		#See how many times each catagory is used
		cat_count = {}
		for cat in self.catagories:
			cat_count[cat] = 0
		for t in self.tours:
			cat_count[t.parent] = 1
		
		#Catagories
		self.parents = {}
		self.tree_catagories = []
		self.children = {}
		for cat in self.catagories:
			if cat_count[cat] > 0:
				#Create the parent
				self.children[cat] = []
				self.tree_catagories.append(cat)
				
				#If it's not hidden, add it.
				if cat.lower() != 'hidden':
					self.parents[cat] = self.tree_store.append(None, [cat, -1])
		
		#Sort the tours
		self.sorted_tours = sorted(self.tours, cmp=lambda x,y: self.TourCmp(x, y))
		
		#Loop through the tours
		for t in self.sorted_tours:
			#Debug
			self.p(t.name)
			self.p(t.parent)
			
			#Add the parent if its not common
			if not t.parent in self.children.keys():
				if t.parent.lower() != 'hidden':
					self.parents[t.parent] = self.tree_store.append(None, [t.parent, -1])
				self.tree_catagories.append(t.parent)
				self.children[t.parent] = []
		
			#Add to tree store if its not a hidden tour
			if t.parent.lower() != 'hidden':
				self.tree_store.append(self.parents[t.parent], [t.name, t.id])
			
			#Add to list of parents children
			self.children[t.parent].append(t.id)
			
		#Set the model
		self.tree_menu.set_model(model=self.tree_store)
		
		#Expand
		self.tree_menu.expand_all()
	
	
	#A function to sort tours
	def TourCmp(self, a, b):
		#print a,b
		if a.pos < b.pos:
			return -1
		elif a.pos > b.pos:
			return 1
		else:
			return 0
	
	
	#Row selected callback
	def row_selected(self, selection, user_param=None):
		if len(selection.get_selected_rows()[1]) > 0:
			#Get the position
			pos = selection.get_selected_rows()[1][0]
			
			#Scroll to the selected value
			self.tree_menu.scroll_to_cell(pos)
			
			#What is the selected value
			if len(pos) == 2:
				try:
					self.load_page(self.children[self.tree_catagories[pos[0]+1]][pos[1]],0)
				except:
					self.p('Could not load ' + pos)