-
Notifications
You must be signed in to change notification settings - Fork 1
/
moshpytt.py
executable file
·1451 lines (1032 loc) · 45.9 KB
/
moshpytt.py
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
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# moshPyTT is a program to view and edit Tesseract boxfiles.
#
#
#
# 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 3 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., 51 Franklin Street, Fifth Floor, Boston,
# MA 02110-1301, USA.
# check pyGTK version
import pygtk
pygtk.require('2.0')
import gtk
import pango
import codecs
import sys
import os
import shutil
import copy
from datetime import datetime
import optparse
#CONVERT A DIRECTORY OF IMAGES TO A DJVU FILE
def main():
"""Parse any arguments, and start moshPyTT"""
parser = optparse.OptionParser(usage='Usage: %prog [-i image file]')
parser.add_option('-i', dest='imageFile', action='store',
help='an image with a corresponding boxfile')
parser.add_option('-d', dest='debug', action='store_true', default=False,
help='show debugging information')
(opts, args) = parser.parse_args()
MoshPyTT(opts)
# parameters
NAME = 'moshPyTT'
VERSION = '0.2'
MENU = \
'''<ui>
<menubar name="MenuBar">
<menu action="File">
<menuitem action="Open"/>
<menuitem action="Save"/>
<menuitem action="SaveAs"/>
<menuitem action="Quit"/>
</menu>
<menu action="Edit">
<menuitem action="Undo"/>
<menuitem action="Redo"/>
<menuitem action="MergeBoxes"/>
<menuitem action="SplitBoxes"/>
<menuitem action="DeleteBoxes"/>
</menu>
<menu action="Help">
<menuitem action="About"/>
<menuitem action="Shortcuts"/>
</menu>
</menubar>
</ui>'''
class TesseractBox:
text = ''
left = None
right = None
top = None
bottom = None
page = None
italic = False
uline = False
bold = False
valid = False # if the box is valid
def make_string(self):
"""Constructs a box string from the box object"""
string = ''
if self.bold:
string += "@"
if self.italic:
string += "$"
if self.uline:
string += "'"
string += '%s %d %d %d %d %d' % (self.text, self.left, self.bottom, self.right, self.top, self.page)
return string
def set_text(self, string):
if type(string) is str or type(string) is unicode:
self.text = string
else:
raise TypeError("Box text must be a string. Received " + str(type(string)))
def check_numbers(self):
"""Checks the box edges to ensure that the "left" edge is really to the
left of the "right" edge, and simlar for the top/bottom"""
if self.left > self.right:
temp = self.left
self.left = self.right
self.right = temp
if self.top < self.bottom:
temp = self.top
self.top = self.bottom
self.bottom = temp
def move(self, direction, step=1):
"""Move the box to one side, in the direction given, by step pixels."""
if direction == 'LEFT':
self.left -= step
self.right -= step
elif direction == 'RIGHT':
self.left += step
self.right += step
elif direction == 'TOP':
self.top += step
self.bottom += step
elif direction == 'BOTTOM':
self.top -= step
self.bottom -= step
def stretch(self, direction, step=1):
"""Stretch the "direction" side of the box by "step" pixels. Negative
step values produce shrinkage of the box"""
if direction == 'LEFT':
self.left -= step
elif direction == 'RIGHT':
self.right += step
elif direction == 'TOP':
self.top += step
elif direction == 'BOTTOM':
self.bottom -= step
elif direction == 'ALL':
self.left -= step
self.right += step
self.top += step
self.bottom -= step
self.check_numbers()
def __init__(self, string=None):
if not string:
return
parts = string.split()
if len(parts) == 6:
try:
self.left = int(parts[1])
self.bottom = int(parts[2])
self.right = int(parts[3])
self.top = int(parts[4])
self.page = int(parts[5])
self.text = parts[0]
self.valid = True
except ValueError: # if the int()s fail, ignore this box, there is something wrong with it
return
attributeCounter = 0
while True:
#don't add attributes we already have, don't add last char
if self.text[attributeCounter] == '$' and not self.italic and attributeCounter +1 < len(self.text):
attributeCounter += 1
self.italic = True
elif self.text[attributeCounter] == '@' and not self.bold and attributeCounter +1 < len(self.text):
attributeCounter += 1
self.bold = True
elif self.text[attributeCounter] == "'" and not self.uline and attributeCounter +1 < len(self.text):
attributeCounter += 1
self.uline = True
#only the first 3 chars can be attrs, or maybe less
if attributeCounter > 2 or attributeCounter+1 >= len(self.text) or self.text[attributeCounter] not in ['@', '$', "'"]:
break
self.text = self.text[attributeCounter:]
def __repr__(self):
return "TesseractBox: "+self.make_string()
def __str__(self):
return self.make_string()
def __unicode__(self):
return self.make_string()
class UndoRedoStack:
def __init__(self):
self.undoStack = []
self.redoStack = []
def undo(self):
"""Grab an item off the stack, if there is one, but leave it in place"""
if len(self.undoStack) > 0:
item = self.undoStack.pop() # pop off the undo stack
self.redoStack.append(item) # and onto the redo stack
return item
else: #there is nothing to undo
return None
def redo(self):
if len(self.redoStack) > 0:
item = self.redoStack.pop() # pop off the redo stack
self.undoStack.append(item) # and onto the redo stack
return item
else: #there is nothing to redo
return None
def add_item(self, item):
self.undoStack.append(item) # add the item to the undo stack
self.redoStack = [] #invalidate the redo stack
class MoshPyTT:
pixbuf = None
newBoxList = None # a temporary list of boxes produced after a merge. If != None, then there are newBoxes to deal with
deleteBoxes = False
boxList = [] # a list of boxes that are selected
blockUndoRedo = False #do not add the next action to the undo/redo stack
userScrolled = False #true if the user overrides the automatic scrolling
userSetAttributes = True #true if a toggling of the attribute button means the box needs to be updated
boxfileChangedSinceSave = False #true if there are unsaved changes
blockUpdates = False #true to prevent update callback firing
changeCounter = 0 #counter of changes to the boxfile
def error_dialog(self, labelText, parent):
dialog = gtk.Dialog('Error', parent, gtk.DIALOG_NO_SEPARATOR
| gtk.DIALOG_MODAL, (gtk.STOCK_OK,
gtk.RESPONSE_OK))
label = gtk.Label(labelText)
dialog.vbox.pack_start(label, True, True, 0)
label.show()
dialog.run()
dialog.destroy()
# CALLBACKS
def on_redraw(self, drawingArea, event):
self.redraw_drawing_area()
def on_mark_set(self, textBuffer, iter, textMark):
cursor = self.textBuffer.get_insert()
iterAtCursor = self.textBuffer.get_iter_at_mark(cursor)
cursorLine = iterAtCursor.get_line()
endLine = self.textBuffer.get_end_iter().get_line()
vAdj = self.textScroll.get_vadjustment()
#if the value is above the current page
value = vAdj.upper * (cursorLine/float(endLine))
if value < vAdj.value:
vAdj.value = value
#if the value is below the current page
value = vAdj.upper * ((cursorLine+1)/float(endLine))
if value > vAdj.value + vAdj.page_size:
vAdj.value = value - vAdj.page_size
self.get_current_box()
def on_buffer_changed(self, event):
self.get_current_box()
def on_insert_text(self, textBuffer, startIter, insertedText, length):
allowUndo = self.on_change()
if allowUndo:
offset = startIter.get_offset()
undoStackItem = {'action':'INS', 'text':insertedText, 'offset':offset}
self.undoRedoStack.add_item( undoStackItem )
def on_delete_range(self, textBuffer, startIter, endIter):
allowUndo = self.on_change()
if allowUndo:
deletedText = self.textBuffer.get_text(startIter, endIter)
offset = startIter.get_offset()
undoStackItem = {'action':'DEL', 'text':deletedText, 'offset':offset}
self.undoRedoStack.add_item( undoStackItem )
def on_change(self):
"""Process actions on a change.
Return false if the action should NOT be added to the undo/redo stack
Returns true if it should
"""
self.boxfileChangedSinceSave = True
self.changeCounter += 1
if self.changeCounter >= self.autosaveChangeLimit:
self.autosave_boxfile()
self.changeCounter = 0
if self.blockUndoRedo: #if the action was blocked
self.blockUndoRedo = False #allow the next one
return False
return True
def on_scroll_image(self, range, scroll, value):
self.userScrolled = True # the user overrides the image scrolling
def on_checkbutton_toggled(self, widget, attribute):
"""An attribute checkbutton was toggled"""
if not self.userSetAttributes:
return
value = widget.get_active()
self.newBoxList = self.boxList #copy the boxlist to prevent a callback messing with it before we use it
for box in self.newBoxList:
if attribute == 'BOLD':
box.bold = value
elif attribute == 'ITALIC':
box.italic = value
elif attribute == 'ULINE':
box.uline = value
self.update_boxes()
def on_find_clicked(self, button, forward=True):
"""One of the find buttons was clicked
If forward is true, find the next example of the given text, otherwise
find the previous one
"""
searchString = self.findEntry.get_text()
iterAtCursor = self.textBuffer.get_iter_at_mark(self.textBuffer.get_insert())
while True:
try:
if forward:
startIter, endIter = iterAtCursor.forward_search(searchString, gtk.TEXT_SEARCH_TEXT_ONLY)
else:
startIter, endIter = iterAtCursor.backward_search(searchString, gtk.TEXT_SEARCH_TEXT_ONLY)
except TypeError:
break
if startIter: #if we found anything
#if the text is previously selected by this function, move to
#end of selection and start again
if startIter.get_offset() == iterAtCursor.get_offset():
iterAtCursor = endIter
continue
self.textBuffer.place_cursor(startIter)
self.textBuffer.move_mark_by_name('selection_bound', endIter)
break
else:
break
def on_entry_key_press(self, entry, event):
control = event.state & gtk.gdk.CONTROL_MASK
shift = event.state & gtk.gdk.SHIFT_MASK
alt = event.state & gtk.gdk.MOD1_MASK
command = None
if control or shift or alt:
print event.keyval
if event.keyval in [gtk.keysyms.KP_Left, gtk.keysyms.KP_4, gtk.keysyms._4, gtk.keysyms.Left]: #Left arrow
command = 'LEFT'
elif event.keyval in [gtk.keysyms.KP_Up, gtk.keysyms.KP_8, gtk.keysyms._8, gtk.keysyms.Up]: # Up arrow
command = 'TOP'
elif event.keyval in [gtk.keysyms.KP_Right, gtk.keysyms.KP_6, gtk.keysyms._6, gtk.keysyms.Right]: # Right arrow
command = 'RIGHT'
elif event.keyval in [gtk.keysyms.KP_Down, gtk.keysyms.KP_2, gtk.keysyms._2, gtk.keysyms.Down]: # Down arrow
command = 'BOTTOM'
elif event.keyval in [gtk.keysyms.KP_Begin, gtk.keysyms.KP_5, gtk.keysyms._5]: # Centre
command = 'ALL'
elif event.keyval in [gtk.keysyms.KP_Insert, gtk.keysyms.KP_0, gtk.keysyms._0]: # Delete the boxes
command = 'DELETE'
elif event.keyval in [gtk.keysyms.KP_End, gtk.keysyms.KP_1, gtk.keysyms._1]: # Merge the boxes
command = 'MERGE'
elif event.keyval in [gtk.keysyms.KP_Page_Down, gtk.keysyms.KP_3, gtk.keysyms._3]: # Split the boxes
command = 'SPLIT'
elif event.keyval in [gtk.keysyms.space, gtk.keysyms.Return, gtk.keysyms.KP_Enter]: # Move to next box
command = 'NEXT'
elif event.keyval in [gtk.keysyms.BackSpace]: # Move to previous box
command = 'PREVIOUS'
elif event.keyval <= 0xFD00: # Update box with character and move to next box
command = 'CHANGECHAR'
if command in ['LEFT', 'RIGHT', 'TOP', 'BOTTOM', 'ALL']:
if control and not shift and not alt:
self.stretch_boxes(command, False)
return True
elif control and shift and not alt:
self.stretch_boxes(command, True)
return True
elif not control and not shift and alt:
self.move_boxes(command)
return True
elif command in ['DELETE']:
if control and not shift and not alt:
self.delete_boxes()
return True
elif command in ['MERGE']:
if control and not shift and not alt:
self.merge_boxes()
return True
elif command in ['SPLIT']:
if control and not shift and not alt:
self.split_boxes()
return True
elif command in ['NEXT']:
self.next_box()
return True
elif command in ['PREVIOUS']:
self.previous_box()
return True
elif command in ['CHANGECHAR']:
self.change_char_in_boxes(event.keyval)
self.next_box()
return True
return False
def stretch_boxes(self, direction, shrink):
if shrink:
step = -1
else:
step = 1
for box in self.boxList:
box.stretch(direction, step)
self.newBoxList = self.boxList
self.update_boxes()
def move_boxes(self, direction):
step = 1
for box in self.boxList:
box.move(direction, step)
self.newBoxList = self.boxList
self.update_boxes()
def change_char_in_boxes(self, keyval):
"""Changes the character in the selected boxes"""
pt = gtk.gdk.keyval_to_unicode(keyval) #Returns Unicode code point, or zero if none found
if pt != 0: # No suitable unicode found, don't change
char = unichr(pt)
for box in self.boxList:
box.set_text(char)
self.newBoxList = self.boxList
self.update_boxes()
def get_current_box(self):
"""If there is a selection, updates the lines which are selected.
Otherwise, updates the line which contains the cursor"""
if self.blockUpdates:
return
bounds = self.textBuffer.get_selection_bounds()
# get all selected lines
if bounds:
topLine = bounds[0].get_line() # top line
btmLine = bounds[1].get_line() # bottom line
# just the line with the cursor
else:
cursor = self.textBuffer.get_mark('insert')
iterAtCursor = self.textBuffer.get_iter_at_mark(cursor)
topLine = btmLine = iterAtCursor.get_line() # this is the line holding the box to draw
#get the textIters wrapping the complete lines
self.topIter = self.textBuffer.get_iter_at_line(topLine) # start of the first selected line
self.btmIter = self.textBuffer.get_iter_at_line(btmLine+1) # start of the line below the selection
self.read_current_box()
def read_current_box(self):
"""Reads the currently selected text into memory, ready for display"""
strings = self.textBuffer.get_text(self.topIter, self.btmIter).split('\n')
self.boxList = []
for i in range(len(strings)):
string = strings[i]
if string == '': #skip blank lines
continue
box = TesseractBox(string)
if box.valid:
self.boxList.append(box)
else:
print 'Invalid line: %s' % string
#TODO highlight line
self.userScrolled = False # regain control of the image scrolling
self.redraw_drawing_area()
def next_box(self):
"""Moves to the next box in the boxfile (by moving the TextBuffer down one line).
If multiple lines are selected, moves to the line after the last selected line."""
bounds = self.textBuffer.get_selection_bounds()
# jump to next line after selection
if bounds:
self.topIter = bounds[1]
# jump to next line after cursor
self.btmIter.forward_line()
# Haven't hit the end
if self.topIter.forward_line():
self.textBuffer.place_cursor(self.topIter)
self.get_current_box() # Redraw
def previous_box(self):
"""Moves to the previous box, or the one before the first selected line."""
bounds = self.textBuffer.get_selection_bounds()
# jump to line before selection
if bounds:
self.btmIter = bounds[0]
# jump to line before cursor
self.btmIter.backward_line()
# Haven't hit the end
if self.topIter.backward_line():
self.textBuffer.place_cursor(self.topIter)
self.get_current_box() # Redraw
def set_checkbox_values(self, box):
"""Set the checkbox values based on a box"""
self.userSetAttributes = False #prevent the toggle checkboxes callback firing
self.italicButton.set_active(box.italic)
self.boldButton.set_active(box.bold)
self.ulineButton.set_active(box.uline)
self.userSetAttributes = True
def set_text_attributes(self, box):
"""Set the text attributes baed on box"""
if box.italic:
self.pangoAttrList.change(pango.AttrStyle(pango.STYLE_ITALIC, 0, -1))
else:
self.pangoAttrList.change(pango.AttrStyle(pango.STYLE_NORMAL, 0, -1))
if box.bold:
self.pangoAttrList.change(pango.AttrWeight(pango.WEIGHT_BOLD, 0, -1))
else:
self.pangoAttrList.change(pango.AttrWeight(pango.WEIGHT_NORMAL, 0, -1))
if box.uline:
self.pangoAttrList.change(pango.AttrUnderline(pango.UNDERLINE_SINGLE, 0, -1))
else:
self.pangoAttrList.change(pango.AttrUnderline(pango.UNDERLINE_NONE, 0, -1))
def set_pen_colour(self, colour):
"""Set the drawing area pen colour"""
parsedColour = gtk.gdk.color_parse(colour)
self.drawingGC.set_rgb_fg_color(parsedColour) # color of rectangle
def redraw_drawing_area(self):
'''redraw area of selected symbol + add rectangle'''
if self.pixbuf and self.drawingArea.window:
vertOffset = int( self.scrolledWindow.get_vadjustment().value )
visibleHeight = int( self.scrolledWindow.get_vadjustment().page_size )
horzOffset = int( self.scrolledWindow.get_hadjustment().value )
visibleWidth = int( self.scrolledWindow.get_hadjustment().page_size )
self.drawingArea.window.draw_pixbuf(self.drawingGC, self.pixbuf,
horzOffset, vertOffset,
horzOffset, vertOffset,
width=int(visibleWidth), height=int(visibleHeight))
if self.boxList:
if not self.userScrolled:
#centre on the first box
hAdj = self.scrolledWindow.get_hadjustment()
newHAdjValue = self.boxList[0].left - visibleWidth/2.0
newHAdjValue = max(0, newHAdjValue)
newHAdjValue = min(hAdj.upper - visibleWidth, newHAdjValue)
#only move the window if it is a "significant" move
if abs(hAdj.value - newHAdjValue) > 100:
hAdj.value = newHAdjValue
vAdj = self.scrolledWindow.get_vadjustment()
newVAdjValue = self.pixbuf.get_height() - self.boxList[0].top - visibleWidth/2.0
newVAdjValue = max(0, newVAdjValue)
newVAdjValue = min(vAdj.upper - visibleHeight, newVAdjValue)
if abs(vAdj.value - newVAdjValue) > 100:
vAdj.value = newVAdjValue
#set checkboxes based on the first box
self.set_checkbox_values(self.boxList[0])
# draw all selected boxes
for box in self.boxList:
if box.text.isupper():
self.set_pen_colour(self.uppercaseColour)
else:
self.set_pen_colour(self.lowercaseColour)
# draw the rectange described by self.box
segments = [(box.left, self.pixbuf.get_height() - box.top),
(box.right, self.pixbuf.get_height() - box.top),
(box.right, self.pixbuf.get_height() - box.bottom),
(box.left, self.pixbuf.get_height() - box.bottom),
(box.left, self.pixbuf.get_height() - box.top)]
self.drawingArea.window.draw_lines(self.drawingGC, segments)
#set the text attributes
self.set_text_attributes(box)
#set the text
self.pangoLayout.set_text(box.text)
(width, height) = self.pangoLayout.get_pixel_size()
textPosX = (box.left + box.right - width) /2.0
textPosY = self.pixbuf.get_height() - box.bottom + self.boxLabelOffset
#draw the text
self.drawingArea.window.draw_layout(self.drawingGC, int(textPosX), int(textPosY), self.pangoLayout)
def check_files(self):
'''
Make sure that the image, box files exists
'''
try:
fc = open(self.loadedImageFilename, 'r')
fc.close()
except IOError:
self.error_dialog('Cannot find the %s file' % self.loadedImageFilename,
self.window)
return False
try:
fb = open(self.loadedBoxFilename, 'r')
fb.close()
except IOError:
self.error_dialog('Cannot find the %s file' % self.loadedBoxFilename,
self.window)
return False
return True
def do_file_open(self, action):
chooser = gtk.FileChooserDialog('Open Image', self.window,
gtk.FILE_CHOOSER_ACTION_OPEN, (gtk.STOCK_CANCEL,
gtk.RESPONSE_CANCEL, gtk.STOCK_OPEN, gtk.RESPONSE_OK))
chooser.set_current_folder(self.currentPath)
filter = gtk.FileFilter()
filter.set_name('TIFF files')
filter.add_pattern('*.tif')
filter.add_pattern('*.tiff')
chooser.add_filter(filter)
filter = gtk.FileFilter()
filter.set_name('Image files')
filter.add_pattern('*.jpg')
filter.add_pattern('*.jpeg')
filter.add_pattern('*.png')
filter.add_pattern('*.bmp')
filter.add_pattern('*.tif')
filter.add_pattern('*.tiff')
chooser.add_filter(filter)
filter = gtk.FileFilter()
filter.set_name('All files')
filter.add_pattern('*')
chooser.add_filter(filter)
response = chooser.run()
if response == gtk.RESPONSE_OK:
self.loadedImageFilename = chooser.get_filename()
self.load_image_and_boxes()
chooser.destroy()
def do_file_save(self, action):
self.save_boxfile()
def do_file_save_as(self, action):
chooser = gtk.FileChooserDialog('Save Boxfile and Image', self.window,
gtk.FILE_CHOOSER_ACTION_SAVE, (gtk.STOCK_CANCEL,
gtk.RESPONSE_CANCEL, gtk.STOCK_SAVE, gtk.RESPONSE_OK))
chooser.set_current_folder(self.currentPath)
filter = gtk.FileFilter()
filter.set_name('Boxfiles')
filter.add_pattern('*.box')
chooser.add_filter(filter)
response = chooser.run()
if response == gtk.RESPONSE_OK:
oldBoxFilename = self.loadedBoxFilename
self.loadedBoxFilename = chooser.get_filename()
# catch no extension
try:
(name, extension) = self.loadedBoxFilename.rsplit('.', 1)
except ValueError: #no extension
name = self.loadedBoxFilename
extension = '.box'
#update filenames
oldImageFilename = self.loadedImageFilename
self.loadedBoxFilename = name + extension
self.loadedImageFilename = name + '.tif'
self.save_boxfile(oldBoxFilename)
#copy image to go with new boxfile
if oldImageFilename != self.loadedImageFilename:
shutil.copyfile(oldImageFilename, self.loadedImageFilename)
self.update_filename()
chooser.destroy()
def autosave_boxfile(self):
"""Save an autosave file"""
string = self.get_all_text()
saveFile = open(self.loadedBoxFilename+'.autosave', 'w')
saveFile.write(string)
saveFile.close()
def remove_autosave_file(self, filename=None):
"""Remove the autosave file, if it exists"""
if filename:
autosaveFilename = filename
else:
autosaveFilename = self.loadedBoxFilename
autosaveFilename += '.autosave'
if os.path.exists(autosaveFilename):
if self.DEBUG:
print 'Removing autosave file: %s' % autosaveFilename
os.remove(autosaveFilename)
def save_boxfile(self, oldFilename=None):
"""Saves the current boxfile to the current filename
The autosave file corresponding to oldfilename, if it exists,
otherwise self.loadedBoxFilename, will be removed
"""
string = self.get_all_text()
saveFile = open(self.loadedBoxFilename, 'w')
saveFile.write(string)
saveFile.close()
if self.DEBUG:
print 'Saved file: %s' % self.loadedBoxFilename
self.remove_autosave_file(oldFilename)
self.boxfileChangedSinceSave = False
def do_undo(self, action):
self.undo_change()
def do_redo(self, action):
self.redo_change()
# HELP ACTIONS ###########
def do_help_about(self, action):
"""Show the About dialog"""
dialog = gtk.Dialog('About %s'%NAME, self.window,
gtk.DIALOG_NO_SEPARATOR | gtk.DIALOG_MODAL,
(gtk.STOCK_OK, gtk.RESPONSE_OK))
dialog.set_size_request(450, 250)
label = gtk.Label('''
%s version %s
Website: moshpytt.googlecode.com
Copyright 2011 John Beard <john.j.beard at gmail.com>
Copyright 2010 Zdenko Podobný <zdenop at gmail.com>
Copyright 2008 Mihail Radu Solcan (djvused and image maps)
Copyright 2007 Cătălin Frâncu <cata at francu.com>
This program is free software: you can redistribute it and/or
modify it under the terms of the GNU General Public License v3
''' % (NAME, VERSION))
label.set_line_wrap(True)
dialog.vbox.pack_start(label, True, True, 0)
label.show()
dialog.run()
dialog.destroy()
def do_help_shortcuts(self, action):
"""Display a dialog showing the keyboard shortcuts"""
dialog = gtk.Dialog('Keyboard shortcuts', self.window,
gtk.DIALOG_NO_SEPARATOR | gtk.DIALOG_MODAL,
(gtk.STOCK_OK, gtk.RESPONSE_OK))
#dialog.set_size_request(450, 250)
label = gtk.Label(
'''Keyboard shortcuts
Directions: 8 - Up, 4 - Left, 6 - Right, 2 - Down, 5 - All
Ctrl-direction: Stretch box in direction
Ctrl-shift-direction: Shrink box in direction
Alt-direction: Move box in direction
Ctrl-0: Delete selected boxes
Ctrl-1: Merge selected boxes
Ctrl-2: Split selected boxes
Ctrl-Z: Undo change
Ctrl-Y: Redo change
''')
label.set_line_wrap(True)
dialog.vbox.pack_start(label, True, True, 0)
label.show()
dialog.run()
dialog.destroy()
def do_merge_boxes(self, action):
self.merge_boxes()
# BOX EDITING ACTIONS #########
def do_delete_boxes(self, action):
self.delete_boxes()
def do_split_boxes(self, action):
self.split_boxes()
def do_quit(self, mi=None, action=None):
if not self.confirm_close():
return True
gtk.main_quit()
def get_all_text(self):
bounds = self.textBuffer.get_bounds()
return self.textBuffer.get_text(bounds[0], bounds[1])
### UNDO/REDO HANDLING ###
def apply_change(self, change):
if not change:
return
# invert the action
if change['action'] == 'INS':
change['action'] = 'DEL'
elif change['action'] == 'DEL':
change['action'] = 'INS'
if change['action'] == 'DEL':
self.blockUndoRedo = True
offset = change['offset']
startIter = self.textBuffer.get_iter_at_offset(offset)
endIter = self.textBuffer.get_iter_at_offset(offset + len(change['text']) )
self.textBuffer.delete(startIter, endIter)
elif change['action'] == 'INS':
self.blockUndoRedo = True
startIter = self.textBuffer.get_iter_at_offset(change['offset'])
self.textBuffer.insert(startIter, change['text'])
def undo_change(self):
change = self.undoRedoStack.undo()
self.apply_change(change)
def redo_change(self):
change = self.undoRedoStack.redo()