Subversion Repositories Scribus

Rev

Rev 3957 | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
3957 mrdocs 1
#!/usr/bin/env python
1048 cbradney 2
# -*- coding: utf-8 -*-
3
 
4
# ****************************************************************************
3957 mrdocs 5
#  This program is free software; you can redistribute it and/or modify
1048 cbradney 6
#  it under the terms of the GNU General Public License as published by
7
#  the Free Software Foundation; either version 2 of the License, or
8
#  (at your option) any later version.
9
#
10
#  This program is distributed in the hope that it will be useful,
11
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
12
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13
#  GNU General Public License for more details.
14
#
15
#  You should have received a copy of the GNU General Public License
16
#  along with this program; if not, write to the Free Software
17
#  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
3957 mrdocs 18
#
1048 cbradney 19
# ****************************************************************************
20
 
21
"""
22
******************************************************************************
23
 
24
DESCRIPTION & USAGE:
540 subik 25
This script needs Tkinter. It will create a GUI with an alphabetical list
26
of fonts using the names as they will be shown in Scribus. User can select
27
one or more fonts and create an example sheet(s) to print or create a PDF
28
from. It is heavily commented to make it easier for the user to adjust it
29
for his / her own needs.
222 Franz 30
 
3957 mrdocs 31
Note: this version needs read/write access to .scribus directory in users
1048 cbradney 32
home. You will also need Python Imaging Library (PIL) installed.
33
If your system does not meet these requirements then change showPreviewPanel
34
to a value of 0. This will disable the new preview features.
540 subik 35
 
1048 cbradney 36
******************************************************************************
540 subik 37
 
1048 cbradney 38
First release    : 30/12/2003
4022 mrdocs 39
This release     : v0.8.1tk (released 4th Dec 2005)
1066 cbradney 40
Copyright        : (C) 2003 - 2005 Steve Callcott
41
Latest releases
42
and support      : www.firstwish.co.uk/sjc/scribus/index.php
43
Maintainer       : Steve Callcott 2003 - 2005
3002 mrdocs 44
Email            : stotte@firstwish.co.uk
540 subik 45
 
46
For revision history see the ChangeLog file.
47
Bugs and future plans are listed in the TODO file.
48
See NEWS for new features since last version.
49
 
4022 mrdocs 50
WHATS NEW v0.8.1tk:
51
After reloading users saved preferences the status bar was not showing
52
correct calculations.
53
Changed text in settings menu.
54
 
3957 mrdocs 55
WHATS NEW v0.8tk Final:
56
Cleaned up the checkbox labels and layout.
3448 mrdocs 57
 
3957 mrdocs 58
WHATS NEW v0.8tk Preview 3:
59
Calls the new Scribus zoomDocument() function to make the completed font
60
sample document fit in Scribus window.
3012 mrdocs 61
 
3957 mrdocs 62
Grey out "Start page number count from first page" when "Print TOC" is
63
not checked as without a table of contents the first page would always
64
start on the same page number making this option irrelevant.
3002 mrdocs 65
 
3957 mrdocs 66
WHATS NEW v0.8tk Preview 2:
67
Replaced the newDoc() with newDocument(). Have not put any fallback code
68
for use with earlier Scribus versions.
69
 
70
When using double sided option we now make use of Scribus ability to display
71
pages side by side as default. You may need to zoom out to view the
72
complete document width.
73
 
74
WHATS NEW v0.8tk Preview 1:
75
Rearanged the initialisation. If no fonts are found for the Table of
76
Contents, page numbers and font sample labels, the script shows a
77
message box listing the problem and a possible solution as well as a message
1072 cbradney 78
to the console.
79
 
3957 mrdocs 80
A Scribus messagebox alerts the user if Tkinter is not found. Previously
81
this message was only printed to the console.
1066 cbradney 82
 
3957 mrdocs 83
Now able to do a dummy run to calculate and report the amount of samples
84
that will fit on a page. This enables the script to correctly calculate
85
how many sheets will be required. Previously it was always assumed that
86
there would be 3 sample blocks on a sheet. This is now not always the case.
540 subik 87
 
3957 mrdocs 88
Added menu. Also added "about" and "settings" dialogs.
89
 
90
Sample rows can be selected or unselected to save on paper. The settings are
91
automatically saved when changed and can be set as user defaults.
92
 
93
User can choose to have page numbers count from first page of the toc instead
94
of the first page of samples. This can be helpful if wanting to quickly look
95
up a font in the toc and then using the Scribus page navigator dialog to go to
96
the actual page on the screen to view it without printing it out.
97
 
98
Added initial support for a sample paragraph. The sample paragraph defaults
99
to "off" due to the amount of space it uses on the page.
100
 
101
Some widgets read their defaults from a config dictionary.
102
 
103
Many code cleanups. Classes used for settings storage have been replaced with
104
dictionaries to make it easier for users to customise.
105
 
1048 cbradney 106
******************************************************************************
540 subik 107
"""
108
 
1048 cbradney 109
import sys
110
import os
3957 mrdocs 111
import cPickle
222 Franz 112
 
3957 mrdocs 113
 
114
showPreviewPanel = 1 # change to 0 to permanently hide the preview
115
TEMP_PATH = os.path.join(os.path.expanduser('~'), '.scribus')
116
CONFIG_PATH = os.path.join(os.path.expanduser('~'), '.scribus/fontsampler')
117
 
118
 
1048 cbradney 119
try:
120
    import scribus
121
except ImportError,err:
3957 mrdocs 122
    print 'This Python script is written for the Scribus scripting interface.'
123
    print 'It can only be run from within Scribus.'
1048 cbradney 124
    sys.exit(1)
222 Franz 125
 
3957 mrdocs 126
 
1048 cbradney 127
try:
128
    from Tkinter import *
129
except ImportError,err:
3957 mrdocs 130
    print 'This script will not work without Tkinter'
131
    scribus.messageBox('Error','This script will not work without Tkinter\nPlease install and try again',
132
                    scribus.ICON_WARNING)
1048 cbradney 133
    sys.exit(1)
134
 
135
 
3957 mrdocs 136
if not os.path.exists(CONFIG_PATH):
137
    try:
138
        print 'Attempting to creating configuration file directory...'
139
        os.mkdir(CONFIG_PATH)
140
        print 'Success, now testing for write access of new directory...'
141
        if os.access(CONFIG_PATH, os.W_OK):
142
            print 'Write access ok.'
143
        else:
144
            print 'Error, unable to write to .scribus/fontsampler directory.'
145
    except:
146
        CONFIG_PATH = ''
147
        print 'Failed to make configuration file directory,'
148
        print 'do you have a .scribus directory in your home directory?'
149
        print 'font sampler will not be able to save your preferences'
1048 cbradney 150
 
151
 
3957 mrdocs 152
try:
153
    import Image
154
except ImportError,err:
155
    print 'You need to install Python Imaging Library (PIL).'
156
    print 'If using gentoo then you need to emerge /dev-python/imaging'
157
    print 'If using an RPM based linux distribution then you add python-imaging or similar.'
158
    print 'Script will continue without the font preview panel.'
159
    showPreviewPanel = 0
1048 cbradney 160
 
161
 
3957 mrdocs 162
try:
163
    import ImageTk
164
except ImportError,err:
165
    print 'Module ImageTk not found, font preview disabled'
166
    showPreviewPanel = 0
1048 cbradney 167
 
3957 mrdocs 168
 
1048 cbradney 169
if showPreviewPanel:
3957 mrdocs 170
    if not os.path.exists(TEMP_PATH):
171
        print '.scribus folder not found, disabling font preview panel'
1048 cbradney 172
        showPreviewPanel = 0
3957 mrdocs 173
    if not os.access(TEMP_PATH, os.W_OK):
174
        print 'Unable to write to .scribus folder, disabling font preview panel'
175
        showPreviewPanel = 0
1048 cbradney 176
 
177
 
3957 mrdocs 178
# A few globals for use later...
179
gSamplePic = None
180
gPreviewId = None
1048 cbradney 181
 
3957 mrdocs 182
#*************************************************************************
1048 cbradney 183
 
4022 mrdocs 184
WINDOW_TITLE = 'Font Sampler v0.8.1tk - Steve Callcott'
3957 mrdocs 185
SUPPORT_PAGE = 'www.firstwish.co.uk/sjc/scribus/index.php'
1048 cbradney 186
 
3957 mrdocs 187
fontsListFixed = (
188
    'Luxi Mono Regular',
189
    'Nimbus Mono L Regular',
190
    'Courier 10 Pitch Regular',
191
    'Courier New Regular',
192
    'Courier Regular',
193
    'Andale Mono Regular',
194
    'Larabiefont Regular'
195
)
222 Franz 196
 
3957 mrdocs 197
fontsListProportional = (
198
    'Nimbus Sans L Regular',
199
    'Luxi Sans Regular',
200
    'Bitstream Vera Sans',
201
    'Helvetica',
202
    'Arial Regular'
203
)
222 Franz 204
 
3957 mrdocs 205
defaultPrefs = {
206
    'wantDoubleSided': 0,
207
    'paperSize':'A4',           # currently PAPER_LETTER or PAPER_A4
208
    'wantTOC': 1,
209
    'wantBindingOffset': 0,
210
    'wantPageNumbers': 1,
211
    'wantPageOneOnFirst': 0,
212
    'wantAlphabet' : 1,
213
    'want6Point' : 1,
214
    'want8Point' : 1,
215
    'want10Point' : 1,
216
    'want12Point' : 1,
217
    'want16Point' : 1,
218
    'want20Point' : 1,
219
    'want32Point' : 1,
220
    'wantParagraph' : 0         # Uses a lot of space so default is off
221
}
222 Franz 222
 
3957 mrdocs 223
userPrefs = {}
222 Franz 224
 
3957 mrdocs 225
geometriesList = [
226
    {
227
        'paperName' : 'A4',
228
        'paperSize' : scribus.PAPER_A4,
229
        'paperWidth' : 595,
230
        'paperHeight' : 842,
231
        'paperTopMargin' : 60,
232
        'paperBottomMargin' : 50,
233
        'paperLeftMargin' : 50,
234
        'paperRightMargin' : 50,
235
        'paperBinding' : 16,
236
        'tocRowsPerPage' : 57,
237
        'paperPageNumVertOffset' : 16
238
    },
239
    {
240
        'paperName' : 'US Letter',
241
        'paperSize' : scribus.PAPER_LETTER,
242
        'paperWidth' : 612,
243
        'paperHeight' : 792,
244
        'paperTopMargin' : 27,
245
        'paperBottomMargin' : 45,
246
        'paperLeftMargin' : 50,
247
        'paperRightMargin' : 50,
248
        'paperBinding' : 18,
249
        'tocRowsPerPage' : 56,
250
        'paperPageNumVertOffset' : 16
251
    }
252
]
222 Franz 253
 
3957 mrdocs 254
# define our data dictionary and some of the data...
255
dD = {
256
    'tocHeaderTitle' : 'Table of Contents',
257
    'tocCharsInRow' : 75,
258
    'previewpanelFontHeight' : 28,
259
    'previewpanelSampleText' : 'Woven silk pyjamas exchanged for blue quartz'
260
}
222 Franz 261
 
3957 mrdocs 262
samplesHeader = {
263
    'fontSize' : 16,
264
    'lineSpace' : 15,
265
    'textHeight' : 23
266
}
222 Franz 267
 
3957 mrdocs 268
# Use \xBC etc to insert Hex ascii chars into the sample strings below.
269
sampleAlphabet = {
270
    'fontSize' : 10.5,
271
    'lineSpace' : 12,
272
    'textString' : 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#?$*&',
273
    'textHeight' : 18
274
}
222 Franz 275
 
3957 mrdocs 276
sample6Point = {
277
    'fontSize' : 6,
278
    'lineSpace' : 6,
279
    'textString' : 'This line is in 6 point',
280
    'textHeight' : 13
281
}
222 Franz 282
 
3957 mrdocs 283
sample8Point = {
284
    'fontSize' : 8,
285
    'lineSpace' : 8,
286
    'textString' : 'This line is in 8 point',
287
    'textHeight' : 16
288
}
289
 
290
sample10Point = {
291
    'fontSize' : 10,
292
    'lineSpace' : 11,
293
    'textString' : 'This line is in 10 point',
294
    'textHeight' : 19
295
}
296
 
297
sample12Point = {
298
    'fontSize' : 12,
299
    'lineSpace' : 11,
300
    'textString' : 'This line is in 12 point',
301
    'textHeight' : 21
302
}
303
 
304
sample16Point = {
305
    'fontSize' : 16,
306
    'lineSpace' : 13,
307
    'textString' : 'This line is in 16 point',
308
    'textHeight' : 26
309
}
310
 
311
sample20Point = {
312
    'fontSize' : 20,
313
    'lineSpace' : 16,
314
    'textString' : 'This line is in 20 point',
315
    'textHeight' : 31
316
}
317
 
318
sample32Point = {
319
    'fontSize' : 32,
320
    'lineSpace' : 29,
321
    'textString' : 'This line is in 32 point',
322
    'textHeight' : 49
323
}
324
 
325
sampleParagraph = {
326
    'fontSize' : 9,
327
    'lineSpace' : 10.8,
328
    'textHeight' : 175
329
}
330
 
331
sampleParagraphText = 'Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Ut a sapien. \
332
Aliquam aliquet purus molestie dolor. Integer quis eros ut erat posuere dictum. \
333
Curabitur dignissim. Integer orci. Fusce vulputate lacus at ipsum. Quisque in libero \
334
nec mi laoreet volutpat. Aliquam eros pede, scelerisque quis, tristique cursus, \
335
placerat convallis, velit. Nam condimentum. Nulla ut mauris. Curabitur adipiscing, \
336
mauris non dictum aliquam, arcu risus dapibus diam, nec sollicitudin quam erat quis \
337
ligula. Aenean massa nulla, volutpat eu, accumsan et, fringilla eget, odio. \
338
Nulla placerat porta justo. Nulla vitae turpis.\n\nPraesent lacus.Lorem ipsum dolor sit \
339
amet, consectetuer adipiscing elit. Pellentesque habitant morbi tristique senectus \
340
et netus et malesuada fames ac turpis egestas. Quisque vel erat eget diam \
341
consectetuer iaculis. Cras ante velit, suscipit et, porta tempus, dignissim quis, \
342
magna. Vivamus viverra, turpis nec rhoncus ultricies, diam turpis eleifend nisl, a \
343
eleifend ante felis ac sapien. Integer bibendum. Suspendisse in mi non neque \
344
bibendum convallis. Suspendisse potenti. Sed sit amet purus at felis adipiscing \
345
aliquam. Vivamus et nisl sit amet mauris aliquet molestie. Integer tortor massa, \
346
aliquam a, lacinia nonummy, sagittis nec, eros.'
347
 
348
#*************************************************************************
349
 
350
def set_font_fixed(fontList):
351
    """Find a matching font for the Table of Contents."""
352
    availableFonts = scribus.getFontNames()
1048 cbradney 353
    found = 0
3957 mrdocs 354
    for f in fontList:
355
        if found:
1048 cbradney 356
            break
3957 mrdocs 357
        for i in availableFonts:
358
            if not found:
1048 cbradney 359
                if f == i:
3957 mrdocs 360
                    return f
1048 cbradney 361
                    found = 1
362
                    break
3957 mrdocs 363
    if not found:
364
        errorList = ''
365
        for j in fontList:
366
            errorList = errorList + j + '\n'
367
        errorMessage ='No suitable fixed width font found.\nPlease install at least one of these fixed width fonts:\n'+errorList
368
        print errorMessage
369
        raise Exception(errorMessage)
222 Franz 370
 
371
 
3957 mrdocs 372
def set_font_proportional(fontList):
373
    """Find a matching font for the page numbers and font names above samples."""
374
    availableFonts = scribus.getFontNames()
1048 cbradney 375
    found = 0
3957 mrdocs 376
    for p in fontList:
377
        if found:
1048 cbradney 378
            break
3957 mrdocs 379
        for i in availableFonts:
380
            if not found:
1048 cbradney 381
                if p == i:
3957 mrdocs 382
                    return p
1048 cbradney 383
                    found = 1
384
                    break
3957 mrdocs 385
    if not found:
386
        errorList = ''
387
        for j in fontList:
388
            errorList = errorList + j + '\n'
389
        errorMessage = 'No suitable proportional font found.\nPlease install at least one of these proportional fonts:\n'+errorList
390
        print errorMessage
391
        raise Exception(errorMessage)
222 Franz 392
 
393
 
3957 mrdocs 394
def save_user_conf(path):
395
    """Save the data to the save file on the path specified by CONFIG_PATH.
222 Franz 396
 
3957 mrdocs 397
    Note initialisation unsets the CONFIG_PATH if it failed to verify or create"""
398
    if not path == '':
399
        try:
400
            file = open(os.path.join(path,'fontsampler.conf'), 'w')
401
            data = {
402
                'a' : defaultPrefs,
403
                'b' : userPrefs
404
            }
405
            cPickle.dump(data, file)
406
            file.close()
407
        except:
408
            print 'failed to save data'
222 Franz 409
 
410
 
3957 mrdocs 411
def restore_user_conf(path):
412
    """Restore the data from the save file on the path specified by CONFIG_PATH."""
413
    try:
414
        file = open(os.path.join(path,'fontsampler.conf'), 'r')
415
        data = cPickle.load(file)
416
        file.close()
417
        defaultPrefs.update(data['a'])
418
        userPrefs.update(data['b'])
419
    except:
420
        userPrefs.update(defaultPrefs)
421
        print 'failed to load saved data so using default values defined in the script'
222 Franz 422
 
423
 
3957 mrdocs 424
def set_page_geometry(dD, geometriesList, paperSize, wantBindingOffset):
425
    """This is the experimental replacement paper size setting function.
222 Franz 426
 
3957 mrdocs 427
    Each paper size and other associated data are stored in a dictionary.
428
    The dictionaries are stored in a list. We copy appropriate dictionary
429
    and custom calculations into a work dictionary for use.
430
    The advantage of this is its easier to add new paper definitions.
431
    Returns a new dictionary, use .update to merge in new values into dD.
432
    """
433
    try:
434
        result={}
435
        for i in geometriesList:
436
            if i['paperName'] == paperSize:
437
                dD.update(i)
222 Franz 438
 
3957 mrdocs 439
        result['paperLeftMarginOdd'] = dD['paperLeftMargin'] + \
440
                                       dD['paperBinding']
441
        result['paperRightMarginEven'] = dD['paperRightMargin'] + \
442
                                         dD['paperBinding']
443
        result['paperTextHeight'] = dD['paperHeight'] - \
444
                                    dD['paperTopMargin'] - \
445
                                    dD['paperBottomMargin']
446
        result['paperMargins'] =  dD['paperLeftMargin'],dD['paperRightMargin'],dD['paperTopMargin'],dD['paperBottomMargin']
447
 
448
        # if we are adding a binding offset to the margins then we will have less width for our text...
449
        if wantBindingOffset:
450
            result['paperTextWidth'] = dD['paperWidth'] - \
451
                                       dD['paperLeftMargin'] - \
452
                                       dD['paperRightMargin'] - \
453
                                       dD['paperBinding'] - \
454
                                       2
455
        else:
456
            result['paperTextWidth'] = dD['paperWidth'] - \
457
                                       dD['paperLeftMargin'] - \
458
                                       dD['paperRightMargin'] - \
459
                                       2
460
        return result
461
    except:
462
        errorMessage = 'set_page_geometry() failure: %s' % sys.exc_info()[1]
463
        print errorMessage
464
 
465
 
466
def set_odd_even(pageNum):
467
    """ Sets the left margin position.
468
 
469
    Checks the number passed to it and sets left margin accordingly.
470
    Call once after each new page is created.
1048 cbradney 471
    Returns 1 if even and 0 if odd page.
472
    """
473
    if pageNum % 2 == 0:
474
        isEvenPage = 1                                          # Even side
475
    else:
476
        isEvenPage = 0                                          # Odd side
222 Franz 477
 
3957 mrdocs 478
    if userPrefs['wantBindingOffset']:
479
        if isEvenPage and userPrefs['wantDoubleSided']:         # Even (when double sided)
480
            dD['paperLeftSide'] = dD['paperLeftMargin'] + 1
1048 cbradney 481
        else:                                                   # Odd side
3957 mrdocs 482
            dD['paperLeftSide'] = dD['paperLeftMarginOdd'] + 1
1048 cbradney 483
    else:                                                       # No binding
3957 mrdocs 484
        dD['paperLeftSide'] = dD['paperLeftMargin'] + 1
1048 cbradney 485
    return isEvenPage
222 Franz 486
 
487
 
3957 mrdocs 488
def draw_sample_row(font, fontSize, lineSpace, textString, x, y, w, h, getSizeOnly):
489
    """Creates one row of samples or a header for the top of the block.
490
 
491
    Called once by draw_sample_block() to create a block label then as many times
492
    as required to create each actual sample found in the list of dictionaries
493
    containing each samples definition.
494
    """
495
    if not getSizeOnly:
1048 cbradney 496
        f = scribus.createText(x, y, w, h)
497
        scribus.insertText(textString, 0, f)
3957 mrdocs 498
        scribus.setFont(font, f)
1048 cbradney 499
        scribus.setFontSize(fontSize, f)
500
        scribus.setLineSpacing(lineSpace, f)
501
        scribus.setTextAlignment(0, f)
502
    return y + h + 1
222 Franz 503
 
504
 
3957 mrdocs 505
def draw_sample_block(fontName, x, y, w, getSizeOnly):
506
    """Drawing of a complete sample block starts from here.
507
 
508
    Iterates through each sample declared in the "samples" tuple. Places one
509
    complete block using the font specified in fontname.
510
    Note top line on page is drawn outside of this function. This ensures ease
511
    of returning same height of every sample block. Line could have been drawn
512
    at top inside this function and page finalised with line at bottom instead.
513
    If getSizeOnly is true then returns the overall height of the entire text
514
    block but without actually placing it.
515
    """
1048 cbradney 516
    startPos = y
3957 mrdocs 517
    # Note there are 2 points of space before horizontal line at bottom of block.
518
    # This 2 points will not appear at top of page so need to add it.
222 Franz 519
 
3957 mrdocs 520
    # set space below horizontal line to the top of the text block
521
    y = y + 4
222 Franz 522
 
3957 mrdocs 523
    # (note there is one extra point inserted by addSampleRow() for each row generated)...
222 Franz 524
 
3957 mrdocs 525
    # first need a header...
526
    y = draw_sample_row(dD['bookstylePropFont'], samplesHeader['fontSize'], samplesHeader['lineSpace'], fontName, x, y, w, samplesHeader['textHeight'], getSizeOnly)
222 Franz 527
 
3957 mrdocs 528
    if userPrefs['wantAlphabet']:
529
        y = draw_sample_row(fontName, sampleAlphabet['fontSize'], sampleAlphabet['lineSpace'], sampleAlphabet['textString'], x, y, w, sampleAlphabet['textHeight'], getSizeOnly)
530
 
531
    if userPrefs['want6Point']:
532
        y = draw_sample_row(fontName, sample6Point['fontSize'], sample6Point['lineSpace'], sample6Point['textString'], x, y, w, sample6Point['textHeight'], getSizeOnly)
533
 
534
    if userPrefs['want8Point']:
535
        y = draw_sample_row(fontName, sample8Point['fontSize'], sample8Point['lineSpace'], sample8Point['textString'], x, y, w, sample8Point['textHeight'], getSizeOnly)
536
 
537
    if userPrefs['want10Point']:
538
        y = draw_sample_row(fontName, sample10Point['fontSize'], sample10Point['lineSpace'], sample10Point['textString'], x, y, w, sample10Point['textHeight'], getSizeOnly)
539
 
540
    if userPrefs['want12Point']:
541
        y = draw_sample_row(fontName, sample12Point['fontSize'], sample12Point['lineSpace'], sample12Point['textString'], x, y, w, sample12Point['textHeight'], getSizeOnly)
542
 
543
    if userPrefs['want16Point']:
544
        y = draw_sample_row(fontName, sample16Point['fontSize'], sample16Point['lineSpace'], sample16Point['textString'], x, y, w, sample16Point['textHeight'], getSizeOnly)
545
 
546
    if userPrefs['want20Point']:
547
        y = draw_sample_row(fontName, sample20Point['fontSize'], sample20Point['lineSpace'], sample20Point['textString'], x, y, w, sample20Point['textHeight'], getSizeOnly)
548
 
549
    if userPrefs['want32Point']:
550
        y = draw_sample_row(fontName, sample32Point['fontSize'], sample32Point['lineSpace'], sample32Point['textString'], x, y, w, sample32Point['textHeight'], getSizeOnly)
551
 
552
    if userPrefs['wantParagraph']:
553
        y = draw_sample_row(fontName, sampleParagraph['fontSize'], sampleParagraph['lineSpace'], sampleParagraphText, x, y, w, sampleParagraph['textHeight'], getSizeOnly)
554
 
555
    y = y + 1   # one extra point of space above bottom Horiz. line
556
 
557
    lineHeight = draw_horiz_line(y, x, w + x, getSizeOnly)
558
    y = y + lineHeight
559
 
1048 cbradney 560
    return y - startPos
222 Franz 561
 
562
 
3957 mrdocs 563
def insert_toc_row(fontName, pageNum, yPos, frame):
564
    """Called once for each content line to be drawn in the text frame."""
1048 cbradney 565
    dotLine = ""
3957 mrdocs 566
    dotQuant = dD['tocCharsInRow'] - len(fontName) - len(str(pageNum)) + 1
1048 cbradney 567
    for i in range(dotQuant):
568
        dotLine = dotLine + '.'
569
    oneLine = fontName + dotLine + str(pageNum) + "\n"
570
    scribus.insertText(oneLine, yPos, frame)
571
    yPos = yPos + len(oneLine) + 0
572
    return yPos
222 Franz 573
 
1048 cbradney 574
 
3957 mrdocs 575
def build_toc_page_template():
576
    """Inserts empty toc template into the currently selected page."""
1048 cbradney 577
    # first put a header on the empty page...
3957 mrdocs 578
    textstring = dD['tocHeaderTitle']
579
    yPos = dD['paperTopMargin'] + 1
580
    header = scribus.createText(dD['paperLeftSide'], yPos, dD['paperTextWidth'], 35)
1048 cbradney 581
    scribus.insertText(textstring, 0, header)
3957 mrdocs 582
    scribus.setFont(dD['bookstylePropFont'], header)
1048 cbradney 583
    scribus.setFontSize(24, header)
584
    scribus.setTextAlignment(1, header)
585
    # now create a text frame for the table of contents...
586
    yPos = yPos + 36
3957 mrdocs 587
    body = scribus.createText(dD['paperLeftSide'], yPos, dD['paperTextWidth'], dD['paperHeight'] - yPos - dD['paperBottomMargin'] - 1)
588
    scribus.setFont(dD['bookstyleFixedFont'], body)
1048 cbradney 589
    scribus.setFontSize(10, body)
590
    scribus.setLineSpacing(12, body)
591
    return body
222 Franz 592
 
593
 
3957 mrdocs 594
def build_toc(tocList):
595
    """Creates all the Table of Contents pages.
596
 
597
    Calls tocPageFramesBuild() to write the header and empty frame for the
598
    toc rows each time a new page is added.
599
    Then calls tocRowAdd() to add each line to the toc frame. Creates new page
600
    each time it completes last row on page.
601
    """
1048 cbradney 602
    rowCount = 0
603
    yPos = 0
604
    tocPageNum = 1
605
    tocPageCount = 1
222 Franz 606
 
1048 cbradney 607
    scribus.newPage(tocPageNum)
3957 mrdocs 608
    isEvenPage = set_odd_even(tocPageNum)
609
    body = build_toc_page_template()             # create frames for new empty page
1048 cbradney 610
    if isEvenPage == 0:
611
        scribus.setTextAlignment(2, body)
612
    else:
613
        scribus.setTextAlignment(0, body)
614
    for i in tocList:
3957 mrdocs 615
        if rowCount == dD['tocRowsPerPage']: # Need to build a new TOC page (count is from zero, not one)
1048 cbradney 616
            tocPageNum = tocPageNum + 1
617
            scribus.newPage(tocPageNum)
3957 mrdocs 618
            isEvenPage = set_odd_even(tocPageNum)
619
            body = build_toc_page_template()
620
            if not isEvenPage:
1048 cbradney 621
                scribus.setTextAlignment(2, body)
622
            else:
623
                scribus.setTextAlignment(0, body)
624
            rowCount = 0
625
            yPos = 0
626
            tocPageCount = tocPageCount + 1
3957 mrdocs 627
        yPos = insert_toc_row(i[0], i[1], yPos, body)
3448 mrdocs 628
        rowCount = rowCount + 1
3957 mrdocs 629
    if userPrefs['wantDoubleSided']:
1048 cbradney 630
        if tocPageCount % 2 != 0:           # Odd page
631
            tocPageNum = tocPageNum + 1
632
            scribus.newPage(tocPageNum)     # Add an extra page if odd number
222 Franz 633
 
634
 
3957 mrdocs 635
def add_page_num(pageNum):
636
    yPos = dD['paperHeight'] - \
637
           dD['paperBottomMargin'] - \
638
           dD['paperPageNumVertOffset']
639
    footer = scribus.createText(dD['paperLeftSide'], yPos, dD['paperTextWidth'], 15)
640
    scribus.insertText('%s' % pageNum, 0, footer)
641
    scribus.setFont(dD['bookstylePropFont'], footer)
1048 cbradney 642
    scribus.setFontSize(9, footer)
643
    scribus.setTextAlignment(1, footer)
644
    scribus.setLineSpacing(10, footer)
222 Franz 645
 
646
 
3957 mrdocs 647
def create_empty_samplepage(pageNum, getSizeOnly):
648
    """Creates a new page and increments page number by one.
649
 
650
    Note getSizeOnly is now evaluated. Will still generate page number increment
651
    but will not actually create the new page or place the number on the page."""
652
    if not getSizeOnly:
653
        scribus.newPage(-1)
654
    pageNum = pageNum + 1
655
    set_odd_even(pageNum)
656
    if not getSizeOnly:
657
        if userPrefs['wantPageNumbers']:
658
            add_page_num(pageNum)
659
    return pageNum
660
 
661
 
662
def draw_horiz_line(yPos, xStart, xEnd, getSizeOnly):
663
    """Draws a line and returns the height.
664
 
665
    If getSizeOnly is set then returns the height it would have
666
    used but without actually creating a line.
667
    """
668
    lineWidth = 1
669
    if not getSizeOnly:
670
        newLine = scribus.createLine(xStart, yPos, xEnd, yPos)
671
        scribus.setLineWidth(lineWidth, newLine)
672
    return lineWidth
673
 
674
 
675
def draw_selection(fontList, getSizeOnly):
676
    """Draws the sample blocks onto the Scribus canvas.
677
 
678
    Measure one font sample block including any horizontal lines and extra
679
    vertical spaces.
680
    Get the amount of vertical space available for the text area between the
681
    top line and top of page number area.
682
    Use these two values to calculate how many complete sample blocks will fit
683
    in the space available. This is the "pageBlocks"
684
    Note we always draw the top horizontal line before placing the blocks. This
685
    is taken into account when calculating the available text area.
686
    Next, if "getSizeOnly" is false we create a page then create the sample
687
    blocks while incrementing a counter until it matches the "pageBlocks".
688
    Reset the counter and create new page. We keep going until we have processed
689
    all the fonts in the selection list.
690
    We update the Scribus progress bar as we create each font sample block.
691
    The returned result is used to update some values in the status bar.
692
    """
3012 mrdocs 693
    progress = 1
694
    scribus.progressReset()
695
    scribus.progressTotal(len(fontList))
1048 cbradney 696
    tocList = []
697
    pageNum = 1
3957 mrdocs 698
    blockCounter = 0
699
    counter = 0
700
    facingPages = scribus.NOFACINGPAGES
701
 
702
    # Just get blocks per page value...
703
    set_odd_even(pageNum)
704
    lineHeight = 1 # include the one point of space below top margin
705
    lineHeight = lineHeight + draw_horiz_line(0, dD['paperLeftSide'], dD['paperLeftSide'] + dD['paperTextWidth'], 1)
706
    usuableArea = dD['paperHeight'] - \
707
                  dD['paperTopMargin'] - \
708
                  lineHeight - \
709
                  dD['paperBottomMargin'] - \
710
                  dD['paperPageNumVertOffset']
711
 
712
    blockHeight = draw_sample_block(fontList[0], dD['paperLeftSide'], 0, dD['paperTextWidth'], 1)
713
    pageBlocks = int(usuableArea / blockHeight)
714
    #print blockHeight
715
    #print "Usuable area %s points high" % usuableArea
716
    #print "Used space on page is %s points high" % (blockHeight * pageBlocks)
717
 
718
    if not getSizeOnly:
719
        # not a dummy run so start by setting up page numbering...
720
        if userPrefs['wantPageOneOnFirst'] and userPrefs['wantTOC']:
721
            tocPageCount = divmod(len(fontList), dD['tocRowsPerPage'])
722
            pageNum = pageNum + tocPageCount[0]
723
            if tocPageCount[1] != 0:
724
                # (adding more to page number as not whole number)
725
                pageNum = pageNum + 1
726
            if userPrefs['wantDoubleSided']:
727
                oddEvenTest = divmod(pageNum, 2)
728
                if oddEvenTest[1] == 0:
729
                    # (adding extra one to start number as odd amount)
730
                    pageNum = pageNum + 1
731
        if userPrefs['wantDoubleSided']:
732
            facingPages = scribus.FACINGPAGES
733
        # now create a new document with empty page and start building...
734
        scribus.newDocument(dD['paperSize'], dD['paperMargins'], scribus.PORTRAIT, 1, scribus.UNIT_POINTS, facingPages, scribus.FIRSTPAGERIGHT)
735
        scribus.zoomDocument(-100)
736
        # A new doc gives us a new page by default so set it up first...
737
        set_odd_even(pageNum)
738
        yPos = dD['paperTopMargin'] + 1
739
        lineHeight = draw_horiz_line(yPos, dD['paperLeftSide'], dD['paperLeftSide'] + dD['paperTextWidth'], getSizeOnly)
740
        yPos = yPos + lineHeight
741
        if userPrefs['wantPageNumbers']:
742
            add_page_num(pageNum)
1048 cbradney 743
        for i in fontList:
3957 mrdocs 744
            # Now place the actual sample block but create a new page if needed...
745
            if counter == pageBlocks:
746
                pageNum = create_empty_samplepage(pageNum, getSizeOnly)
747
                yPos = dD['paperTopMargin'] + 1
748
                lineHeight = draw_horiz_line(yPos, dD['paperLeftSide'], dD['paperLeftSide'] + dD['paperTextWidth'], getSizeOnly)
749
                yPos = yPos + lineHeight
750
                counter = 0
751
            blockHeight = draw_sample_block(i, dD['paperLeftSide'], yPos, dD['paperTextWidth'], getSizeOnly)
752
            yPos = yPos + blockHeight
3012 mrdocs 753
            # and also increment the Scribus progress bar...
754
            scribus.progressSet(progress)
755
            progress = progress + 1
3957 mrdocs 756
            # Add current font to TOC...
757
            tocList.append([i, pageNum])
758
            counter = counter + 1
759
        if userPrefs['wantTOC']:
760
            # Insert table of contents - (before page numbering)...
761
            build_toc(tocList)
1048 cbradney 762
        scribus.gotoPage(1)
3957 mrdocs 763
    return pageBlocks
222 Franz 764
 
765
 
3957 mrdocs 766
def preview_font(app, fontName):
1048 cbradney 767
    """Gets the named font and puts a sample in the preview panel.
768
 
769
    Pick up the temp sample qpixmap file and display it in a canvas object
770
    The temp file is put in the users ".scribus" folder and cleaned up on exit.
771
    We create samplePic as a global as a workaround because the reference count
772
    does not increase when we add the image to the canvas. Therefore python
773
    garbage collection removes our image before we have even displayed it.
774
    Note app.previewPanel is the actual canvas.
775
    """
3957 mrdocs 776
    global gSamplePic
777
    global gPreviewId
778
    scribus.renderFont(fontName, os.path.join(TEMP_PATH,'temp079r.bmp'),dD['previewpanelSampleText'],dD['previewpanelFontHeight'])
1072 cbradney 779
    try:
3957 mrdocs 780
        tempPic = Image.open(os.path.join(TEMP_PATH,'temp079r.bmp'))
781
        tempPic.save(os.path.join(TEMP_PATH,'temp079r.jpeg'),format='JPEG')
782
        tempImage = Image.open(os.path.join(TEMP_PATH,'temp079r.jpeg'))
1072 cbradney 783
        imgDimen = tempPic.getbbox()
3957 mrdocs 784
        gSamplePic = ImageTk.PhotoImage(tempImage)
1072 cbradney 785
        # To center the image use "Half display height minus half the image height"
786
        # preview panel is allegedly 56 (60 less a 2 pixel border top and bottom)
3957 mrdocs 787
        # need to be lower than that to look correct visually...
1072 cbradney 788
        topEdge = (32 - (imgDimen[3] / 2))
3957 mrdocs 789
        gPreviewId = app.previewPanel.create_image(5, topEdge, anchor=NW, image=gSamplePic)
790
        os.remove(os.path.join(TEMP_PATH,'temp079r.bmp'))
791
        os.remove(os.path.join(TEMP_PATH,'temp079r.jpeg'))
1072 cbradney 792
    except IOError:
3957 mrdocs 793
        gSamplePic = None
794
        gPreviewId = app.previewPanel.create_image(0, 0, anchor=NW, image=gSamplePic)
1048 cbradney 795
    return
796
 
797
 
3957 mrdocs 798
class AboutDialog(Toplevel):
799
 
800
    def __init__(self, parent):
801
        Toplevel.__init__(self, parent)
802
        self.transient(parent)
803
        self.title('About')
804
        self.parent = parent
805
        self.result = None
806
        self.resizable(0, 0)
807
 
808
        infoLabel = Label(self, text=WINDOW_TITLE+'\nSupport page at %s' % SUPPORT_PAGE)
809
        infoLabel.pack(padx=5, pady=5)
810
        # now the frame for contents...
811
        contentFrame = Frame(self)
812
        self.btnOk = Button(contentFrame, text='OK', command=self.ok, default=ACTIVE)
813
        self.btnOk.pack(side=LEFT, padx=5, pady=5)
814
        contentFrame.pack()
815
        self.bind('<Return>', self.ok)
816
        self.grab_set()
817
        self.protocol('WM_DELETE_WINDOW', self.ok)
818
        self.initial_focus = self.btnOk
819
        self.wait_window(self)
820
 
821
    def ok(self, event=None):
822
        self.withdraw()
823
        self.update_idletasks()
824
        self.parent.focus_set()
825
        self.destroy()
826
 
827
 
828
class ConfigurationDialog(Toplevel):
829
 
830
    def __init__(self, parent):
831
        Toplevel.__init__(self, parent)
832
        self.transient(parent)
833
        self.title('Configuration')
834
        self.parent = parent
835
        self.result = None
836
        self.resizable(0, 0)
837
 
838
        # Create outer frame...
839
        self.topFrame = Frame(self, bd=1, relief=FLAT)
840
        self.topFrame.grid(row=0, column=0, padx=5, pady=5)
841
 
842
        self.paperSizeLabel = Label(self.topFrame, text='Sample Rows:')
843
        self.paperSizeLabel.grid(row=0, column=0, sticky=W)
844
 
845
        # This frame holds each sample selector...
846
        self.sampleSelectFrame = Frame(self.topFrame, bd=1, relief=RIDGE)
847
        self.sampleSelectFrame.grid(row=1, column=0, padx=0, pady=2)
848
 
849
        # now create the sample selector widgets for the frame...
850
        self.__wantAlphabet = IntVar()
851
        self.btnWantAlphabet = Checkbutton(self.sampleSelectFrame, text='want alphabet row', variable=self.__wantAlphabet, offvalue=0, onvalue=1, command=self.__sampleSelectionClick)
852
        self.btnWantAlphabet.grid(row=0, column=0, padx=10, pady=0, sticky=W)
853
        if userPrefs['wantAlphabet']:
854
            self.btnWantAlphabet.select()
855
 
856
        self.__want6Point = IntVar()
857
        self.btnWant6Point = Checkbutton(self.sampleSelectFrame, text='want 6 point row', variable=self.__want6Point, offvalue=0, onvalue=1, command=self.__sampleSelectionClick)
858
        self.btnWant6Point.grid(row=1, column=0, padx=10, pady=0, sticky=W)
859
        if userPrefs['want6Point']:
860
            self.btnWant6Point.select()
861
 
862
        self.__want8Point = IntVar()
863
        self.btnWant8Point = Checkbutton(self.sampleSelectFrame, text='want 8 point row', variable=self.__want8Point, offvalue=0, onvalue=1, command=self.__sampleSelectionClick)
864
        self.btnWant8Point.grid(row=2, column=0, padx=10, pady=0, sticky=W)
865
        if userPrefs['want8Point']:
866
            self.btnWant8Point.select()
867
 
868
        self.__want10Point = IntVar()
869
        self.btnWant10Point = Checkbutton(self.sampleSelectFrame, text='want 10 point row', variable=self.__want10Point, offvalue=0, onvalue=1, command=self.__sampleSelectionClick)
870
        self.btnWant10Point.grid(row=3, column=0, padx=10, pady=0, sticky=W)
871
        if userPrefs['want10Point']:
872
            self.btnWant10Point.select()
873
 
874
        self.__want12Point = IntVar()
875
        self.btnWant12Point = Checkbutton(self.sampleSelectFrame, text='want 12 point row', variable=self.__want12Point, offvalue=0, onvalue=1, command=self.__sampleSelectionClick)
876
        self.btnWant12Point.grid(row=4, column=0, padx=10, pady=0, sticky=W)
877
        if userPrefs['want12Point']:
878
            self.btnWant12Point.select()
879
 
880
        self.__want16Point = IntVar()
881
        self.btnWant16Point = Checkbutton(self.sampleSelectFrame, text='want 16 point row', variable=self.__want16Point, offvalue=0, onvalue=1, command=self.__sampleSelectionClick)
882
        self.btnWant16Point.grid(row=5, column=0, padx=10, pady=0, sticky=W)
883
        if userPrefs['want16Point']:
884
            self.btnWant16Point.select()
885
 
886
        self.__want20Point = IntVar()
887
        self.btnWant20Point = Checkbutton(self.sampleSelectFrame, text='want 20 point row', variable=self.__want20Point, offvalue=0, onvalue=1, command=self.__sampleSelectionClick)
888
        self.btnWant20Point.grid(row=6, column=0, padx=10, pady=0, sticky=W)
889
        if userPrefs['want20Point']:
890
            self.btnWant20Point.select()
891
 
892
        self.__want32Point = IntVar()
893
        self.btnWant32Point = Checkbutton(self.sampleSelectFrame, text='want 32 point row', variable=self.__want32Point, offvalue=0, onvalue=1, command=self.__sampleSelectionClick)
894
        self.btnWant32Point.grid(row=7, column=0, padx=10, pady=0, sticky=W)
895
        if userPrefs['want32Point']:
896
            self.btnWant32Point.select()
897
 
898
        self.__wantParagraph = IntVar()
899
        self.btnParagraphSelect = Checkbutton(self.sampleSelectFrame, text='want sample paragraph', variable=self.__wantParagraph, offvalue=0, onvalue=1, command=self.__sampleSelectionClick)
900
        self.btnParagraphSelect.grid(row=8, column=0, padx=10, pady=0, sticky=W)
901
        if userPrefs['wantParagraph']:
902
            self.btnParagraphSelect.select()
903
 
904
        self.paperSizeLabel = Label(self.topFrame, text='Paper Sizes:')
905
        self.paperSizeLabel.grid(row=2, column=0, sticky=W)
906
 
907
        self.paperSizeFrame = Frame(self.topFrame, bd=1, relief=RIDGE)
908
        self.paperSizeFrame.grid(row=3, column=0, padx=0, pady=2, sticky=W)
909
 
910
        self.__paper = StringVar()
911
        self.a4papersizeSelect = Radiobutton(self.paperSizeFrame, text='A4', variable=self.__paper, value='A4', command=self.__paperSelectionClick)
912
        self.a4papersizeSelect.grid(row=1, column=0, padx=10, sticky=W)
913
        self.uspapersizeSelect = Radiobutton(self.paperSizeFrame, text='US Letter', variable=self.__paper, value='US Letter', command=self.__paperSelectionClick)
914
        self.uspapersizeSelect.grid(row=2, column=0, padx=10, sticky=W)
915
 
916
        # set to match prefs...
917
        if userPrefs['paperSize'] == 'US Letter':
918
            self.uspapersizeSelect.select()
919
        if userPrefs['paperSize'] == 'A4':
920
            self.a4papersizeSelect.select()
921
 
922
        self.btnFrame = Frame(self.topFrame)
923
        self.btnFrame.grid(row=4, column=0, padx=10, pady=2)
924
        self.btnOk = Button(self.btnFrame, text='OK', command=self.ok)
925
        self.btnOk.grid(row=2, column=0, pady=5)
926
        self.bind('<Return>', self.ok)
927
        self.grab_set()
928
        self.initial_focus = self.btnOk
929
        self.wait_window(self)
930
 
931
 
932
    def __sampleSelectionClick(self):
933
        """Get and store all the selections.
934
 
935
        Just assigns the lot at once. Not worth being picky and only
936
        assigning values that have changed since last time.
937
        """
938
        userPrefs['wantAlphabet'] = self.__wantAlphabet.get()
939
        userPrefs['want6Point'] = self.__want6Point.get()
940
        userPrefs['want8Point'] = self.__want8Point.get()
941
        userPrefs['want10Point'] = self.__want10Point.get()
942
        userPrefs['want12Point'] = self.__want12Point.get()
943
        userPrefs['want16Point'] = self.__want16Point.get()
944
        userPrefs['want20Point'] = self.__want20Point.get()
945
        userPrefs['want32Point'] = self.__want32Point.get()
946
        userPrefs['wantParagraph'] = self.__wantParagraph.get()
947
        self.parent.statusbarUpdate()
948
 
949
    def __paperSelectionClick(self):
950
        userPrefs['paperSize'] = self.__paper.get()
951
        self.parent.statusbarUpdate()
952
 
953
    def ok(self, event=None):
954
        dD.update(set_page_geometry(dD, geometriesList, userPrefs['paperSize'], userPrefs['wantBindingOffset']))
955
        self.withdraw()
956
        self.update_idletasks()
957
        self.parent.focus_set()
958
        self.destroy()
959
 
960
 
222 Franz 961
class Application(Frame):
3957 mrdocs 962
 
1048 cbradney 963
    def __init__(self, master = None):
964
        Frame.__init__(self, master)
222 Franz 965
 
1048 cbradney 966
        self.grid()
222 Franz 967
 
3002 mrdocs 968
        # Remove maximise button and resize. Not good to allow resizable window
969
        # because the listboxes are fixed width...
3957 mrdocs 970
        self.master.resizable(0, 0)
222 Franz 971
 
3957 mrdocs 972
        # build the menu...
973
        menubar = Menu(self)
974
        settingsmenu = Menu(menubar, tearoff=0)
975
        settingsmenu.add_command(label='Configuration', command=self.__configurationDlgShow)
976
        settingsmenu.add_separator()
4022 mrdocs 977
        settingsmenu.add_command(label='Save current settings', command=self.__saveCurrentSettingsAsDefaults)
978
        settingsmenu.add_command(label='Load saved settings', command=self.__restoreCurrentSettingsFromDefault)
3957 mrdocs 979
 
980
        menubar.add_cascade(label='Settings', menu=settingsmenu)
981
        helpmenu = Menu(menubar, tearoff=0)
982
        helpmenu.add_command(label='About', command=self.__aboutDlgShow)
983
        menubar.add_cascade(label='Help', menu=helpmenu)
984
        # display menu...
985
        self.master.config(menu=menubar)
986
 
1048 cbradney 987
        # now start adding our widgets starting with the top frame...
988
        self.listbox_frame = Frame(self)
989
        self.listbox_frame.grid(row=0, column=0, sticky=EW)
222 Franz 990
 
1048 cbradney 991
        # left hand listbox assembly
992
        self.leftListbox_frame = Frame(self.listbox_frame, borderwidth=1, relief=SUNKEN)
993
        self.leftListbox_frame.grid(row=1, column=0)
222 Franz 994
 
3957 mrdocs 995
        self.leftLabel = Label(self.listbox_frame, text='Available Fonts')
1048 cbradney 996
        self.leftLabel.grid(row=0, column=0, sticky=NS)
222 Franz 997
 
1048 cbradney 998
        self.yScroll1 = Scrollbar(self.leftListbox_frame, orient=VERTICAL)
999
        self.yScroll1.grid(row=0, column=1, sticky=NS)
1000
        self.xScroll1 = Scrollbar(self.leftListbox_frame, orient=HORIZONTAL)
1001
        self.xScroll1.grid(row=1, column=0, sticky=EW)
222 Franz 1002
 
1048 cbradney 1003
        self.listbox1 = Listbox(self.leftListbox_frame,
1004
            xscrollcommand=self.xScroll1.set,
1005
            yscrollcommand=self.yScroll1.set,
1006
            selectmode=EXTENDED,
1007
            height=20, width=40)
1008
        self.listbox1.grid(row=0, column=0, sticky=NSEW)
3957 mrdocs 1009
        self.xScroll1['command'] = self.listbox1.xview
1010
        self.yScroll1['command'] = self.listbox1.yview
222 Franz 1011
 
1048 cbradney 1012
        def __listbox1KeyRelease(event):
1013
            """Check if an Up or Down key has been pressed and released and
3957 mrdocs 1014
            if so the preview panel is refreshed. If the keys are held down
1015
            the file system slows the scroll. Need a timer here to delay
1048 cbradney 1016
            updates."""
3957 mrdocs 1017
            if (event.keysym == 'Down' or event.keysym == 'Up'):
1048 cbradney 1018
                __listbox1DoLogicCallback(self)
222 Franz 1019
 
1048 cbradney 1020
        def __listbox1SingleClick(event):
1021
            """Call this first when listbox1 is clicked with mouse to put focus
1022
            into the listbox. Note we call when mouse click is released, not pressed,
1023
            due to the fact that the listbox does not change the selection until the button
1024
            is released."""
1025
            self.listbox1.focus_set()
1026
            __listbox1DoLogicCallback(self)
3957 mrdocs 1027
        self.listbox1.bind('<ButtonRelease-1>', __listbox1SingleClick)
222 Franz 1028
 
1048 cbradney 1029
        def __listbox1DoLogicCallback(event):
3957 mrdocs 1030
            """Decides if current selection should be previewed.
1066 cbradney 1031
 
1048 cbradney 1032
            Start by counting items in selection list and if equal to one then
1033
            show selected font, ignoring if more or less than one. Then also
3957 mrdocs 1034
            set up buttons logic depending on selection. We bind the FocusIn
1048 cbradney 1035
            to this too so button logic and preview gets updated when focus
1036
            enters the listbox.
3957 mrdocs 1037
            """
1048 cbradney 1038
            # note we are not making use of "self.listbox1.get(ACTIVE)" due to
1039
            # it not getting the real active name. Always one selection behind
1040
            # even though we are doing all this in the ButtonRelease event.
1041
            # Have made a change here. If more than one font name is selected
1042
            # then we just empty the preview.
1043
            names = self.listbox1.curselection()
1044
            if len(names) == 1:
1045
                selectedFont = self.listbox1.get(names[0])
1046
                self.__curSelectedItem(selectedFont)
1047
            else:
1048
                try:
1049
                    app.previewPanel.delete(previewId)
1050
                except:
1051
                    pass
1052
            #else:
3957 mrdocs 1053
                #selectedFont = self.listbox1.get(ACTIVE)
1048 cbradney 1054
                #print selectedFont  # for testing
1055
                #if selectedFont != "":
3957 mrdocs 1056
                    #self.__curSelectedItem(selectedFont)
222 Franz 1057
 
1048 cbradney 1058
            # Now do the button logic...
1059
            self.listbox2.selection_clear(0,END)
1060
            self.__setUpDownActive(0, 0)    # Force a disable if in other box
1061
            if self.listbox1.size() > 0:
1062
                self.__setSelButtonsActive(0, 1)
1063
            else:
1064
                self.__setSelButtonsActive(0, 0)
3957 mrdocs 1065
 
1066
        self.listbox1.bind('<FocusIn>', __listbox1DoLogicCallback)
1048 cbradney 1067
        self.listbox1.bind('<Any-KeyRelease>', __listbox1KeyRelease)
222 Franz 1068
 
1048 cbradney 1069
        def __listbox1DoubleClickCallback(event):
1070
            """The single click event will fire also when left listbox
1071
            is double clicked but we are detecting the single click button up event."""
1072
            self.__listSelectionToRight()
222 Franz 1073
 
3957 mrdocs 1074
        self.listbox1.bind('<Double-Button-1>', __listbox1DoubleClickCallback)
1075
 
1048 cbradney 1076
        # middle button frame assembly
1077
        self.midbutton_frame = Frame(self.listbox_frame)
1078
        self.midbutton_frame.grid(row=0, rowspan=2, column=1, sticky=NSEW)
222 Franz 1079
 
3957 mrdocs 1080
        self.rsingleButton = Button(self.midbutton_frame, state='disabled', text='>', command=self.__rsingleButtonClick)
1048 cbradney 1081
        self.rsingleButton.grid(row=0, column=0, padx=5, pady=5, sticky=EW)
3957 mrdocs 1082
        self.rdoubleButton = Button(self.midbutton_frame, text='>>', command=self.__rdoubleButtonClick)
1048 cbradney 1083
        self.rdoubleButton.grid(row=1, column=0, padx=5, pady=5, sticky=EW)
222 Franz 1084
 
3957 mrdocs 1085
        self.itemupButton = Button(self.midbutton_frame, state='disabled', text='Up', command=self.__itemupButtonClick)
1048 cbradney 1086
        self.itemupButton.grid(row=2, column=0, padx=5, pady=5, sticky=EW)
3957 mrdocs 1087
        self.itemdownButton = Button(self.midbutton_frame, state='disabled', text='Down', command=self.__itemdownButtonClick)
1048 cbradney 1088
        self.itemdownButton.grid(row=3, column=0, padx=5, pady=5, sticky=EW)
222 Franz 1089
 
3957 mrdocs 1090
        self.lsingleButton = Button(self.midbutton_frame, state='disabled', text='<', command=self.__lsingleButtonClick)
1048 cbradney 1091
        self.lsingleButton.grid(row=4, column=0, padx=5, pady=5, sticky=EW)
3957 mrdocs 1092
        self.ldoubleButton = Button(self.midbutton_frame, state='disabled', text='<<', command=self.__ldoubleButtonClick)
1048 cbradney 1093
        self.ldoubleButton.grid(row=5, column=0, padx=5, pady=5, sticky=EW)
222 Franz 1094
 
1048 cbradney 1095
        # Right hand listbox assembly
1096
        self.rightListbox_frame = Frame(self.listbox_frame, borderwidth=1, relief=SUNKEN)
1097
        self.rightListbox_frame.grid(row=1, column=2)
222 Franz 1098
 
3957 mrdocs 1099
        self.rightLabel = Label(self.listbox_frame, text='Selected Fonts')
1048 cbradney 1100
        self.rightLabel.grid(row=0, column=2, sticky=NS)
222 Franz 1101
 
1048 cbradney 1102
        self.yScroll2 = Scrollbar(self.rightListbox_frame, orient=VERTICAL)
1103
        self.yScroll2.grid(row=0, column=1, sticky=NS)
1104
        self.xScroll2 = Scrollbar(self.rightListbox_frame, orient=HORIZONTAL)
1105
        self.xScroll2.grid(row=1, column=0, sticky=EW)
222 Franz 1106
 
1048 cbradney 1107
        self.listbox2 = Listbox(self.rightListbox_frame,
1108
            xscrollcommand=self.xScroll2.set,
1109
            yscrollcommand=self.yScroll2.set,
1110
            selectmode=EXTENDED,
1111
            height=20, width=40)
1112
        self.listbox2.grid(row=0, column=0, sticky=NSEW)
3957 mrdocs 1113
        self.xScroll2['command'] = self.listbox2.xview
1114
        self.yScroll2['command'] = self.listbox2.yview
222 Franz 1115
 
1048 cbradney 1116
        def __listbox2SingleClick(event):
1117
            """Similar to __listbox1SingleClick()."""
1118
            self.listbox2.focus_set()
1119
            __listbox2DoLogicCallback(self)
3957 mrdocs 1120
        self.listbox2.bind('<ButtonRelease-1>', __listbox2SingleClick)
222 Franz 1121
 
1048 cbradney 1122
        def __listbox2KeyRelease(event):
3957 mrdocs 1123
            if (event.keysym == 'Down' or event.keysym == 'Up'):
1048 cbradney 1124
                __listbox2DoLogicCallback(self)
222 Franz 1125
 
1048 cbradney 1126
        def __listbox2DoLogicCallback(event):
3957 mrdocs 1127
            """Similar to __listbox1DoLogicCallback()."""
1048 cbradney 1128
            names = self.listbox2.curselection()
1129
            if len(names) == 1:
1130
                selectedFont = self.listbox2.get(names[0])
1131
                self.__curSelectedItem(selectedFont)
1132
            else:
1133
                try:
1134
                    app.previewPanel.delete(previewId)
1135
                except:
1136
                    pass
222 Franz 1137
 
1048 cbradney 1138
            # Now do the button logic...
1139
            self.listbox1.selection_clear(0,END)
1140
            self.__testUpDownState()
1141
            if self.listbox2.size() > 0:
1142
                self.__setSelButtonsActive(1, 0)
1143
            else:
1144
                self.__setSelButtonsActive(0, 0)
3957 mrdocs 1145
        self.listbox2.bind('<FocusIn>', __listbox2DoLogicCallback)
1048 cbradney 1146
        self.listbox2.bind('<Any-KeyRelease>', __listbox2KeyRelease)
222 Franz 1147
 
1048 cbradney 1148
        def __listbox2DoubleClickCallback(event):
1149
            """Similar to __listbox1DoubleClickCallback()."""
1150
            self.__listSelectionToLeft()
3957 mrdocs 1151
        self.listbox2.bind('<Double-Button-1>', __listbox2DoubleClickCallback)
222 Franz 1152
 
1048 cbradney 1153
        # now draw the bottom font preview frame if required...
1154
        if showPreviewPanel:
1155
            self.preview_frame = Frame(self)
1156
            self.preview_frame.grid(row=1, column=0, sticky=EW)
3957 mrdocs 1157
            self.previewPanel = Canvas(self.preview_frame, height=60, bg='white', bd=2, relief=SUNKEN)
1048 cbradney 1158
            self.previewPanel.pack(fill=X)
222 Franz 1159
 
1048 cbradney 1160
        # now draw the bottom controls frame...
1161
        self.controls_frame = Frame(self)
1162
        self.controls_frame.grid(row=2, column=0, sticky=EW)
222 Franz 1163
 
3957 mrdocs 1164
        # create a container...
1165
        self.button_frame1 = Frame(self.controls_frame, bd=1, relief=RIDGE)
1166
        self.button_frame1.grid(row=0, column=0, padx=10, pady=2)
1167
        # create and add page number selection button...
1168
        self.__wantPageNum = IntVar()
1169
        self.pagenumSelect = Checkbutton(self.button_frame1, text='Print page numbers', variable=self.__wantPageNum, offvalue=0, onvalue=1, command=self.__pageNumberSelectButtonClick)
1048 cbradney 1170
        self.pagenumSelect.grid(row=0, column=0, padx=0, sticky=W)
222 Franz 1171
 
3957 mrdocs 1172
        # create a container...
1173
        self.button_frame2 = Frame(self.controls_frame, bd=1, relief=RIDGE)
1174
        self.button_frame2.grid(row=0, column=1, padx=10, pady=2)
1175
        # create and add the TOC selector...
1176
        self.__wantToc = IntVar()
1177
        self.tocSelect = Checkbutton(self.button_frame2, text='Print table of contents', variable=self.__wantToc, offvalue=0, onvalue=1, command=self.__tocSelectButtonClick)
1178
        self.tocSelect.grid(row=0, column=0, padx=0, sticky=W)
1179
        # create and add page one on first selector...
1180
        self.__wantPageOneOnFirst = IntVar()
1181
        self.btnPageOneOnFirst = Checkbutton(self.button_frame2, text='Page count includes TOC', variable=self.__wantPageOneOnFirst, offvalue=0, onvalue=1, command=self.__wantPageOneOnFirstClick)
1182
        self.btnPageOneOnFirst.grid(row=1, column=0, padx=0, sticky=W)
1183
 
1184
        # create a container...
1185
        self.button_frame3 = Frame(self.controls_frame, bd=1, relief=RIDGE)
1186
        self.button_frame3.grid(row=0, column=2, padx=10, pady=2)
1187
        # create and add the binding offset...
1188
        self.__wantBindingOffset = IntVar()
1189
        self.bindingoffsetSelect = Checkbutton(self.button_frame3, text='Extra offset for binding', variable=self.__wantBindingOffset, offvalue=0, onvalue=1, command=self.__bindingoffsetSelectButtonClick)
1048 cbradney 1190
        self.bindingoffsetSelect.grid(row=0, column=0, sticky=W)
3957 mrdocs 1191
        # create and add the double sided selection buttons...
1192
        self.__wantDoubleSided = IntVar()
1193
        self.doublesidedSelect = Checkbutton(self.button_frame3, text='Double sided pages', variable=self.__wantDoubleSided, offvalue=0, onvalue=1, command=self.__doubleSidedSelectButtonClick)
1048 cbradney 1194
        self.doublesidedSelect.grid(row=1, column=0, rowspan=2, sticky=W)
222 Franz 1195
 
1048 cbradney 1196
        # now the ok and cancel buttons...
3957 mrdocs 1197
        self.cancelButton = Button(self.controls_frame, text='Cancel', command=self.__cancelButtonClick)
1048 cbradney 1198
        self.cancelButton.grid(row=0, column=3, padx=5)
3957 mrdocs 1199
        self.okButton = Button(self.controls_frame, text='OK', state='disabled', command=self.__okButtonClick)
1048 cbradney 1200
        self.okButton.grid(row=0, column=4, padx=5)
222 Franz 1201
 
1048 cbradney 1202
        # now create the bottom status bar frame and contents...
1203
        self.status_frame = Frame(self)
1204
        self.status_frame.grid(row=3, column=0, sticky=E+W)
1205
        self.status0 = Label(self.status_frame, bd=1, relief=SUNKEN, anchor=W)
1206
        self.status0.pack(side=LEFT)
1207
        self.status1 = Label(self.status_frame, bd=1, relief=SUNKEN, anchor=W)
1208
        self.status1.pack(side=LEFT)
1209
        self.status2 = Label(self.status_frame, bd=1, relief=SUNKEN, anchor=W)
3957 mrdocs 1210
        self.status2.pack(side=LEFT)
1211
        self.status3 = Label(self.status_frame, bd=1, relief=SUNKEN, anchor=W)
1212
        self.status3.pack(side=LEFT)
1213
        self.statusPaperSize = Label(self.status_frame, bd=1, relief=SUNKEN, anchor=W)
1214
        self.statusPaperSize.pack(fill=X)
222 Franz 1215
 
1048 cbradney 1216
    def statusbarUpdate(self):
3957 mrdocs 1217
        """Draws the status bar contents.
1218
 
1219
        Note "draw_selection()" does a dummy run to count the amount of sample
1220
        blocks on a sheet.
1221
        TODO: Statusbar setting and recalculation should be separated. Just recalc
1222
        and refresh panels as required instead of all of them each time.
1223
        """
1048 cbradney 1224
        available = self.listbox1.size()
1225
        selected = self.listbox2.size()
1226
        size = FloatType(selected)
3957 mrdocs 1227
        blocksPerSheet = draw_selection(scribus.getFontNames(), 1)
1228
        value = size / blocksPerSheet
1048 cbradney 1229
        pages = IntType(value)                  # Get whole part of number
1230
        value = value - pages                   # Remove whole number part
1231
        if value > 0:                           # Test remainder
1232
            pages = pages + 1                   # Had remainder so add a page
3957 mrdocs 1233
        self.status0['text'] = 'Fonts available: %s   ' % (available + selected)
1234
        self.status1['text'] = 'Fonts selected: %s   ' % selected
1235
        self.status2['text'] = 'Sheets required: %s   ' % pages
1236
        self.status3['text'] = 'Fonts per sheet: %s   ' % blocksPerSheet
1237
        self.statusPaperSize['text'] = 'Paper size: %s   ' % userPrefs['paperSize']
222 Franz 1238
 
1048 cbradney 1239
    def __listSelectionToRight(self):
1240
        toMoveRight = ListType(self.listbox1.curselection())
1241
        self.listbox1.selection_clear(0,END)
1242
        toMoveRight.reverse()   # reverse list so we delete from bottom of listbox first
1243
        tempList = []
1244
        for i in toMoveRight:
1245
            tempList.insert(0,self.listbox1.get(i)) # gets the actual strings (reverse again)
1246
            self.listbox1.delete(i)
1247
        for j in tempList:
1248
            self.listbox2.insert(END, j)
1249
        self.__setButtonsState()
1250
        self.__setSelButtonsActive(0, 0)
1251
        self.statusbarUpdate()
222 Franz 1252
 
1048 cbradney 1253
    def __listSelectionToLeft(self):
1254
        toMoveLeft = ListType(self.listbox2.curselection())
1255
        toMoveLeft.reverse()
1256
        self.listbox2.selection_clear(0,END)
1257
        for i in toMoveLeft:
1258
            self.listbox1.insert(END, self.listbox2.get(i)) # Insert it at the end
1259
            self.listbox2.delete(i)
1260
        fontList = ListType(self.listbox1.get(0, END))      # Copy contents to a list type
1261
        self.listbox1.delete(0, END)                        # Remove all contents
1262
        fontList.sort()                                     # Use sort method of list
1263
        for j in fontList:
1264
            self.listbox1.insert(END, j)                    # Replace with sorted version
1265
        self.__setButtonsState()
1266
        self.__setSelButtonsActive(0, 0)
1267
        self.statusbarUpdate()
222 Franz 1268
 
1048 cbradney 1269
    def __listAllToRight(self):
1270
        fontList = self.listbox1.get(0, END)    # Get each font name into a list
1271
        for i in fontList:
1272
            self.listbox2.insert(END, i)        # Copy each one
1273
        self.listbox1.delete(0, END)            # All done so empty the left listbox
1274
        self.__setButtonsState()
1275
        self.__setSelButtonsActive(0, 0)
1276
        self.statusbarUpdate()
222 Franz 1277
 
1048 cbradney 1278
    def __listAllToLeft(self):
3957 mrdocs 1279
        """Moves all selected fonts back to the left hand pane.
1280
 
1281
        Note we just clear both panes then reload the left listbox in correct
1282
        order from scratch as this is probably quicker than moving each
1283
        item individually.
1284
        """
1048 cbradney 1285
        self.listbox1.delete(0, END)
1286
        fontList = scribus.getFontNames()
1287
        fontList.sort()
1288
        for i in fontList:
1289
            self.listbox1.insert(END, i)
1290
        self.listbox2.delete(0, END)
1291
        self.__setButtonsState()
1292
        self.__setSelButtonsActive(0, 0)
1293
        self.statusbarUpdate()
222 Franz 1294
 
1048 cbradney 1295
    def __setSelButtonsActive(self, selToRight, selToLeft):
1296
        # The "selection" buttons are the ones with ">"  and "<"  on them
1297
        if selToRight == 1:
1298
            self.lsingleButton['state'] = NORMAL
1299
        else:
1300
            self.lsingleButton['state'] = DISABLED
1301
        if selToLeft == 1:
1302
            self.rsingleButton['state'] = NORMAL
1303
        else:
1304
            self.rsingleButton['state'] = DISABLED
222 Franz 1305
 
1048 cbradney 1306
    def __setAllButtonsActive(self, allToRight, allToLeft):
1307
        # The "all" buttons are the ones with ">>"  and "<<"  on them
1308
        if allToRight == 1:
1309
            self.rdoubleButton['state'] = NORMAL
1310
        else:
1311
            self.rdoubleButton['state'] = DISABLED
1312
        if allToLeft == 1:
1313
            self.ldoubleButton['state'] = NORMAL
1314
        else:
1315
            self.ldoubleButton['state'] = DISABLED
222 Franz 1316
 
1048 cbradney 1317
    def __setButtonsState(self):
1318
        if self.listbox2.size() > 0 and self.listbox1.size() > 0:
1319
            self.__setAllButtonsActive(1, 1)
1320
            self.okButton['state'] = NORMAL
1321
        elif self.listbox2.size() == 0:
1322
            self.__setAllButtonsActive(1, 0)
1323
            self.okButton['state'] = DISABLED
1324
        elif self.listbox1.size() == 0:
1325
            self.__setAllButtonsActive(0, 1)
1326
            self.okButton['state'] = NORMAL
222 Franz 1327
 
1048 cbradney 1328
    def __itemUp(self):
1329
        """Test if one item is selected then move it up one position."""
1330
        selection = self.listbox2.curselection()
3957 mrdocs 1331
        if len(selection) == 1:
1048 cbradney 1332
            indexId = IntType(selection[0]) # Get the first (only) item as integer type
1333
            if indexId > 0:
1334
                fontString = self.listbox2.get(indexId)
1335
                self.listbox2.delete(indexId)
1336
                newPos = indexId - 1
1337
                self.listbox2.selection_clear(0, END)
1338
                self.listbox2.insert(newPos, fontString)
1339
                self.listbox2.see(newPos - 10)  # Scrolls listbox automatically into view if req.
1340
                self.listbox2.selection_set(newPos)
1341
                self.listbox2.activate(newPos)  # make focus follow selection
1342
                self.__testUpDownState()  # note tests only after an item has been moved
222 Franz 1343
 
1048 cbradney 1344
    def __itemDown(self):
1345
        """Test if one item is selected then move it down one position."""
1346
        limit = self.listbox2.size()
1347
        selection = self.listbox2.curselection()
1348
        if len(selection) == 1:
1349
            indexId = IntType(selection[0])
1350
            if indexId < limit - 1:
1351
                fontString = self.listbox2.get(indexId)
1352
                self.listbox2.delete(indexId)
1353
                newPos = indexId + 1
1354
                self.listbox2.selection_clear(0, END)
1355
                self.listbox2.insert(newPos, fontString)
1356
                self.listbox2.see(newPos + 10)
1357
                self.listbox2.selection_set(newPos)
1358
                self.listbox2.activate(newPos)  # make focus follow selection
1359
                self.__testUpDownState()
222 Franz 1360
 
1048 cbradney 1361
    def __setUpDownActive(self, up, down):
3957 mrdocs 1362
        """Just sets the buttons active or inactive.
1363
 
1364
        See testUpDown() for the actual evaluation
1365
        """
1048 cbradney 1366
        if up == 1:
1367
            self.itemupButton['state'] = NORMAL
1368
        else:
1369
            self.itemupButton['state'] = DISABLED
1370
        if down == 1:
1371
            self.itemdownButton['state'] = NORMAL
1372
        else:
1373
            self.itemdownButton['state'] = DISABLED
222 Franz 1374
 
1048 cbradney 1375
    def __testUpDownState(self):
3957 mrdocs 1376
        """Only enable the up and down buttons when just a single item is selected.
222 Franz 1377
 
3957 mrdocs 1378
        Enable should be applied to up, down or both depending on its
1379
        position in the listbox. At all other times disable both.
1380
        """
1048 cbradney 1381
        # Get a count of how many items are currently selected...
1382
        selection = list(self.listbox2.curselection())
1383
        tcount = 0
1384
        for sel in selection:
1385
            tcount = tcount + 1
222 Franz 1386
 
1048 cbradney 1387
        position = 0
1388
        if tcount == 1:
1389
            position = IntType(selection[0])
222 Franz 1390
 
1048 cbradney 1391
        # If one selected and there is more than one item in the listbox then ok...
1392
        if tcount == 1 and self.listbox2.size() > 1:
1393
            # Now test the position of the selected line...
1394
            if position > 0 and position < self.listbox2.size() - 1:    # Both
1395
                self.__setUpDownActive(1, 1)
1396
            # If not one less or lesser from the bottom (listbox.count-1?) then gray the down button.
1397
            elif position == self.listbox2.size() - 1:                  # Up only
1398
                self.__setUpDownActive(1, 0)
1399
            # If not one or more from the top then gray up button.
1400
            elif position == 0:                                         # Down only
1401
                self.__setUpDownActive(0, 1)
1402
        else:
1403
            self.__setUpDownActive(0, 0)
222 Franz 1404
 
1048 cbradney 1405
    def __curSelectedItem(self, selectedFont):
1406
        """Send the selected font to the preview function if preview available."""
1407
        if showPreviewPanel:
3957 mrdocs 1408
            preview_font(self, selectedFont)
222 Franz 1409
 
1048 cbradney 1410
    # create the button events...
1411
    def __rsingleButtonClick(self):
1412
        self.__listSelectionToRight()
751 subik 1413
 
1048 cbradney 1414
    def __rdoubleButtonClick(self):
1415
        self.__listAllToRight()
1416
 
1417
    def __lsingleButtonClick(self):
1418
        self.__listSelectionToLeft()
1419
        self.__testUpDownState()
1420
 
1421
    def __ldoubleButtonClick(self):
1422
        self.__listAllToLeft()
1423
        self.__testUpDownState()
1424
 
1425
    def __itemupButtonClick(self):
1426
        self.__itemUp()
1427
 
1428
    def __itemdownButtonClick(self):
1429
        self.__itemDown()
1430
 
3957 mrdocs 1431
    def __tocSelectButtonClick(self):
1432
        userPrefs['wantTOC'] = self.__wantToc.get()
1433
        if userPrefs['wantTOC']:
1434
            self.btnPageOneOnFirst['state'] = NORMAL
1435
        else:
1436
            self.btnPageOneOnFirst['state'] = DISABLED
1437
 
1438
    def __pageNumberSelectButtonClick(self):
1439
        userPrefs['wantPageNumbers'] = self.__wantPageNum.get()
1440
 
1441
    def __bindingoffsetSelectButtonClick(self):
1442
        userPrefs['wantBindingOffset'] = self.__wantBindingOffset.get()
1443
        dD.update(set_page_geometry(dD, geometriesList, userPrefs['paperSize'], userPrefs['wantBindingOffset']))
1444
 
1445
    def __doubleSidedSelectButtonClick(self):
1446
        userPrefs['wantDoubleSided'] = self.__wantDoubleSided.get()
1447
 
1448
    def __wantPageOneOnFirstClick(self):
1449
        userPrefs['wantPageOneOnFirst'] = self.__wantPageOneOnFirst.get()
1450
 
1048 cbradney 1451
    def __cancelButtonClick(self):
3957 mrdocs 1452
        """We exit the app here if user presses cancel."""
1048 cbradney 1453
        self.master.destroy()
1454
 
3957 mrdocs 1455
    def __okButtonClick(self):
1456
        """User presses ok, so lets create the pages."""
1457
        save_user_conf(CONFIG_PATH)
1458
        draw_selection(self.listbox2.get(0, END), 0)
1459
        self.master.destroy()
1048 cbradney 1460
 
3957 mrdocs 1461
    def __configurationDlgShow(self):
1462
        """Opens the configuration dialog where user can set up the options"""
1463
        configs = ConfigurationDialog(self)
1464
        self.statusbarUpdate()
1048 cbradney 1465
 
3957 mrdocs 1466
    def __saveCurrentSettingsAsDefaults(self):
1467
        """Stores current settings as defaults."""
1468
        defaultPrefs.update(userPrefs)
1469
        save_user_conf(CONFIG_PATH)
1048 cbradney 1470
 
3957 mrdocs 1471
    def __restoreCurrentSettingsFromDefault(self):
1472
        """Restores current settings from defaults."""
1473
        userPrefs.update(defaultPrefs)
1474
        self.initialiseWidgets()
4022 mrdocs 1475
        self.statusbarUpdate()
1048 cbradney 1476
 
3957 mrdocs 1477
    def initialiseWidgets(self):
1478
        if userPrefs['wantPageNumbers']:
1479
            self.pagenumSelect.select()
1480
        else:
1481
            self.pagenumSelect.deselect()
1482
        if userPrefs['wantTOC']:
1483
            self.tocSelect.select()
1484
            self.btnPageOneOnFirst['state'] = NORMAL
1485
        else:
1486
            self.tocSelect.deselect()
1487
            self.btnPageOneOnFirst['state'] = DISABLED
1488
        if userPrefs['wantBindingOffset']:
1489
            self.bindingoffsetSelect.select()
1490
        else:
1491
            self.bindingoffsetSelect.deselect()
1492
        if userPrefs['wantDoubleSided']:
1493
            self.doublesidedSelect.select()
1494
        else:
1495
            self.doublesidedSelect.deselect()
1496
        if userPrefs['wantPageOneOnFirst']:
1497
            self.btnPageOneOnFirst.select()
1498
        else:
1499
            self.btnPageOneOnFirst.deselect()
1048 cbradney 1500
 
3957 mrdocs 1501
    def __aboutDlgShow(self):
1502
        """Brings up a dialog with support url etc."""
1503
        about = AboutDialog(self)
1504
 
1505
 
1506
def setup_tk():
1048 cbradney 1507
    """Create and setup the Tkinter app."""
1508
    root = Tk()
1509
    app = Application(root)
3957 mrdocs 1510
    app.master.title(WINDOW_TITLE)
1048 cbradney 1511
 
3957 mrdocs 1512
    # now get a list of all the fonts Scribus knows about...
1048 cbradney 1513
    fontList = scribus.getFontNames()
1514
    fontList.sort()
3957 mrdocs 1515
    # and load the list into the GUI listbox...
1048 cbradney 1516
    for i in fontList:
1517
        app.listbox1.insert(END, i)
3957 mrdocs 1518
    app.sampleBlocksPerPage = draw_selection(scribus.getFontNames(), 1)
1519
    # now set the status bar message...
1520
    app.statusbarUpdate()
1521
    # set up widgets using data from userPrefs...
1522
    app.initialiseWidgets()
1523
    return app
1048 cbradney 1524
 
3957 mrdocs 1525
def initialisation():
1526
    """Test for suitable fonts and on success creates tkinter app."""
1527
    try:
1528
        dD['bookstyleFixedFont'] = set_font_fixed(fontsListFixed)
1529
        dD['bookstylePropFont'] = set_font_proportional(fontsListProportional)
1530
    except:
1531
        scribus.messageBox('Font problem',
1532
                           '%s' % sys.exc_info()[1],
1533
                           scribus.ICON_WARNING)
1534
        sys.exit(1)
1535
    # load users saved defaults...
1536
    restore_user_conf(CONFIG_PATH)
1537
    # get and set the initial paper size to match default radiobutton selection...
1538
    dD.update(set_page_geometry(dD, geometriesList, userPrefs['paperSize'], userPrefs['wantBindingOffset']))
1539
    # Made it this far so its time to create our Tkinter app...
1540
    app = setup_tk()
1541
    # now show the main window and wait for user to do something...
1542
    app.mainloop()
1048 cbradney 1543
 
3957 mrdocs 1544
 
1048 cbradney 1545
def main(argv):
1546
    """Application initialization, font checks and initial setup."""
3957 mrdocs 1547
    initialisation()
1048 cbradney 1548
 
1549
 
1550
def main_wrapper(argv):
1551
    """The main_wrapper() function disables redrawing, sets a sensible generic
1552
    status bar message, and optionally sets up the progress bar. It then runs
1553
    the main() function. Once everything finishes it cleans up after the main()
1554
    function, making sure everything is sane before the script terminates."""
1555
    try:
3957 mrdocs 1556
        scribus.statusMessage('Running script...')
1048 cbradney 1557
        scribus.progressReset()
1558
        main(argv)
1559
    finally:
1560
        # Exit neatly even if the script terminated with an exception,
1561
        # so we leave the progress bar and status bar blank and make sure
1562
        # drawing is enabled.
1563
        if scribus.haveDoc():
1564
            scribus.setRedraw(True)
3957 mrdocs 1565
        scribus.statusMessage('')
1048 cbradney 1566
        scribus.progressReset()
1567
 
1568
 
1569
# This code detects if the script is being run as a script, or imported as a module.
1570
# It only runs main() if being run as a script. This permits you to import your script
1571
# and control it manually for debugging.
1572
if __name__ == '__main__':
1573
    main_wrapper(sys.argv)
1574