Subversion Repositories Scribus

Rev

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

Rev Author Line No. Line
12781 subik 1
#!/usr/bin/python
2
# -*- coding: utf-8 -*-
3
 
4
"""
5
ABOUT THIS SCRIPT:
6
 
13058 subik 7
ColorChart.py allows a user to create color charts with all
8
the colors of a given scribus document.
9
It generates a color field for each color and a description
10
of the color, containing the color name, the CMYK values and
11
the RGB values.
12781 subik 12
 
13058 subik 13
If there is a document opened in scribus, ColorChart uses this
14
document as color source and creates a new document with the
15
color chart.
16
If there is no document opened in scribus, ColorChart displays
17
a file open dialog to allow the user to chose a scribus file
18
to generate a colorchart of.
19
You will be asked to give a name for the color chart. This name
20
will be displayed in the pages headlines.
12781 subik 21
############################
22
 
23
LICENSE:
24
 
25
This program is free software; you can redistribute it and/or modify
26
it under the terms of the GNU General Public License as published by
27
the Free Software Foundation; either version 2 of the License, or
28
(at your option) any later version.
29
 
30
This program is distributed in the hope that it will be useful,
31
but WITHOUT ANY WARRANTY; without even the implied warranty of
32
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
33
GNU General Public License for more details.
34
 
35
You should have received a copy of the GNU General Public License
36
along with this program; if not, write to the Free Software
18123 mrdocs 37
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
12781 subik 38
 
39
Author: Sebastian Stetter
40
please report bugs to: scribusscript@sebastianstetter.de
41
"""
42
from __future__ import division
43
import sys
44
__version__=1.1
45
try:
46
    # Please do not use 'from scribus import *' . If you must use a 'from import',
47
    # Do so _after_ the 'import scribus' and only import the names you need, such
48
    # as commonly used constants.
49
    import scribus
50
except ImportError,err:
51
    print "This Python script is written for the Scribus scripting interface."
52
    print "It can only be run from within Scribus."
53
    sys.exit(1)
54
 
55
####################
56
# IMPORTS GO HERE  #
57
####################
58
 
59
COLOR_FIELD_HEIGHT=25
60
#space between colorfields
61
HSPACE=5
62
VSPACE=4
63
#space for header and footer
64
HEADERSIZE = 10
65
FOOTERSIZE = 5
66
TEXT_BOX_WIDTH = 50
67
global pageTitle
68
pageTitle="COLOR CHART"
69
 
70
def drawHeaderFooter(pagetitle):
71
    """draw some info on the pages"""
72
    # get page size
73
    pageSize=scribus.getPageSize()
74
    pageWidth=pageSize[0]
75
    pageHeight=pageSize[1]
76
    #pageMargins
77
    pageMargins=scribus.getPageMargins()
78
    topMargin=pageMargins[0]
79
    leftMargin=pageMargins[1]
80
    rightMargin=pageMargins[2]
81
    bottomMargin=pageMargins[3]
13058 subik 82
 
12781 subik 83
    #create textbox and insert text for header
84
    textbox=scribus.createText(leftMargin, topMargin,  pageWidth-leftMargin-rightMargin, HEADERSIZE)
85
    #set proper font size and alignment
86
    scribus.setFontSize(18, textbox)
22258 gpittman 87
    scribus.setTextColor("Black",textbox)
12781 subik 88
    scribus.setTextAlignment(scribus.ALIGN_CENTERED, textbox)
89
    #load the string into the textbox
90
    headerstring=pagetitle
91
    scribus.insertText(headerstring, 0, textbox)
13058 subik 92
 
12781 subik 93
    #create textbox and insert text for footer
94
    textbox=scribus.createText(leftMargin, pageHeight-bottomMargin-FOOTERSIZE,  pageWidth-leftMargin-rightMargin, FOOTERSIZE)
95
    #set proper font size and alignment
96
    scribus.setFontSize(9, textbox)
22258 gpittman 97
    scribus.setTextColor("Black",textbox)
12781 subik 98
    scribus.setTextAlignment(scribus.ALIGN_LEFT, textbox)
99
    #load the string into the textbox
100
    footerstring="Created using ColorChart.py V %s script for Scribus by Sebastian Stetter - http://www.sebastianstetter.de" % str(__version__)
101
    scribus.insertText(footerstring, 0, textbox)
102
 
13058 subik 103
 
104
def getSpotColors():
105
    """ Get spot colors from an original document.
106
        Must be called after getColorsFromDocument().
107
    """
108
    ret = {}
109
    for color in scribus.getColorNames():
110
        ret[color] = scribus.isSpotColor(color)
111
    return ret
112
 
113
 
12781 subik 114
def getColorsFromDocument():
115
    """gets colors from opend document. if there is no document, display dialog to chose a file. returns a list[name,c,m,y,k]"""
116
    def getColors():
117
        """gets the colors and returns a list[name,c,m,y,k]"""
118
        colorNames=scribus.getColorNames()
119
        list=[]
120
        scribus.statusMessage("Reading Colors...")
121
        stepsTotal=len(colorNames)
122
        scribus.progressTotal(stepsTotal)
123
        steps=0
124
        for name in colorNames:
125
            color=scribus.getColor(name)
126
            listitem=[name, color[0], color[1],  color[2],  color[3]]
127
            list.append(listitem)
128
            #update progress bar
129
            steps=steps+1
130
            scribus.progressSet(steps)
131
        return list
132
 
133
    #check if we have a document - otherwise display open file dialog
17395 fschmid 134
    if scribus.haveDoc() > 0:
12781 subik 135
        pass
136
        list=getColors()
137
        return list
138
    else:
139
        pass
140
        #display file open dialog
141
        file=scribus.fileDialog("ColorChart by Sebastian Stetter",  'Scribus files(*.sla *.SLA *.sla.gz *.SLA.GZ)')
142
        #open file
143
        try:
144
            scribus.openDoc(file)
145
        except:
146
            scribus.messageBox("ColorChart by Sebastian Stetter", "could not open file")
147
            sys.exit()
148
        list=getColors()
149
        return list
150
 
151
def prepareDocument():
152
    """creates the new document, sets up colors """
153
    colorList = getColorsFromDocument()
13058 subik 154
    spotDict = getSpotColors()
12781 subik 155
    scribus.statusMessage("Preparing new document...")
156
    scribus.newDocument(scribus.PAPER_A4,  (15,15,  20, 20),  scribus.PORTRAIT, 1, scribus.UNIT_POINTS,  scribus.PAGE_1, 0, 1)
157
    scribus.setUnit(scribus.UNIT_MILLIMETERS)
158
    #delete existing colors
159
    cols = scribus.getColorNames()
160
    for col in cols:
161
        scribus.deleteColor(col, "None")
13058 subik 162
 
12781 subik 163
    #create our new colors
164
    for color in colorList:
165
        cname=color[0]
166
        c = int(color[1])
167
        m = int(color[2])
168
        y = int(color[3])
169
        k = int(color[4])
170
        scribus.defineColor(cname,  c, m, y, k )
13058 subik 171
        if spotDict.has_key(cname):
172
            scribus.setSpotColor(cname, spotDict[cname])
173
 
12781 subik 174
    #get the pageTitle form user and store it in PageTitle
175
    global pageTitle
176
    pageTitle=scribus.valueDialog("ColorChart by Sebastian Stetter", "Please enter document title", "Scribus COLOR CHART")
177
    drawHeaderFooter(pageTitle)
178
 
179
def createPage():
180
    """appends a new page"""
181
    scribus.newPage(-1) #append new page
182
    #new page - new header and footer
183
    drawHeaderFooter(pageTitle)
184
 
185
 
186
def rgbhex(r,g,b):
187
    '''convert rgb values in 0-255 style to hex string in #000000 to #ffffff style'''
188
    hr=hex(r)
189
    hr = hr.replace("0x", "")
190
    if len(hr)== 0:
191
        hr = "00"
192
    elif len(hr)==1:
193
        hr = "0"+hr
194
    else:
195
        pass
196
    hg=hex(g)
197
    hg = hg.replace("0x", "")
198
    if len(hg)== 0:
199
        hg = "00"
200
    elif len(hg)==1:
201
        hg = "0"+hg
202
    else:
203
        pass
204
    hb=hex(b)  
205
    hb = hb.replace("0x", "")
206
    if len(hb)== 0:
207
        hb = "00"
208
    elif len(hb)==1:
209
        hb = "0"+hb
210
    else:
211
        pass
212
    rgbstring="#"+hr+hg+hb
213
    rgbstring=rgbstring.upper()
214
    return rgbstring
215
 
216
 
217
def drawColor(colorname, h, v, width,  height): #h horizontal position, v vertical position
13058 subik 218
    """draws a color chart field with its caption for the given colorname at the h and v position
219
    """
12781 subik 220
    #get cmyk values and convert them to 0 - 255 values
221
    color = scribus.getColor(colorname)
222
    c= int(round(color[0]/2.55))
223
    m=int(round(color[1]/2.55))
224
    y=int(round(color[2]/2.55))
225
    k=int(round(color[3]/2.55))
226
    #get rgb color
227
    rgbcolor=scribus.getColorAsRGB(colorname)
228
    r=rgbcolor[0]
229
    g=rgbcolor[1]
230
    b=rgbcolor[2]
231
    #get webcolor
232
    webcolor=rgbhex(r, g, b)
233
    #but String for Textbox together
13058 subik 234
    colorDisplay = colorname
235
    if scribus.isSpotColor(colorname):
236
        colorDisplay += " (Spot Color)"
237
    colorstring="%s\nC %i, M %i, Y %i, K %i, \nR %i, G %i, B %i \nRGB: %s" %(colorDisplay, c, m, y, k, r, g, b,  webcolor)
238
 
12781 subik 239
    #draw rectangle and set colors
240
    rect=scribus.createRect(h, v, width,  height)
241
    scribus.setFillColor(colorname, rect)
242
    #if total amount of color is < 20 draw outline in Black for rectangle, else in same color
243
    if c +m+y+k < 20:
244
        scribus.setLineColor("Black", rect)
245
    else:
246
        scribus.setLineColor(colorname, rect)
247
    #create textbox and insert text
248
    textbox=scribus.createText(h+width+5, v, 50, height)
249
    #set proper font size
250
    scribus.setFontSize(11, textbox)
22258 gpittman 251
    scribus.setTextColor("Black",textbox)
12781 subik 252
    scribus.setTextAlignment(scribus.ALIGN_LEFT, textbox)
253
    #load the string into the textbox
254
    scribus.insertText(colorstring, 0, textbox)
255
 
256
 
257
def createChart():
258
    """actually handles the whole chart creation process"""
259
    prepareDocument()
260
    # get page size
261
    pageSize=scribus.getPageSize()
262
    pageWidth=pageSize[0]
263
    pageHeight=pageSize[1]
264
    #pageMargins
265
    pageMargins=scribus.getPageMargins()
266
    topMargin=pageMargins[0]
267
    leftMargin=pageMargins[1]
268
    rightMargin=pageMargins[2]
269
    bottomMargin=pageMargins[3]
13058 subik 270
 
12781 subik 271
    #color field dimensions
272
    colorFieldWidth= pageWidth - leftMargin - rightMargin - (TEXT_BOX_WIDTH+HSPACE) #50+5 is the with of the textbox plus the space between textbox and colorfield
13058 subik 273
 
12781 subik 274
    #how much space does one field use?
275
    vSpaceUsedByField = COLOR_FIELD_HEIGHT+VSPACE
13058 subik 276
 
12781 subik 277
    #how much space is available per row?
278
    vSpaceAvailable=pageHeight-topMargin-bottomMargin-HEADERSIZE-FOOTERSIZE
13058 subik 279
 
12781 subik 280
    #counts the colorFields created for a page. reset this variable after creation of new page
281
    colorFieldCounter=0
13058 subik 282
 
12781 subik 283
    #get list of all colors in document
284
    colorList = scribus.getColorNames()
285
    #prepare the progressbar
286
    colorNumber=len(colorList)
287
    scribus.progressTotal(colorNumber)
288
    #@TODO: implement possibility to abort script (button2=scribus.BUTTON_CANCEL) buttons should return int 1 or 2
289
    #scribus.messageBox("ColorChart Script by Sebastian Stetter", "...going to create a chart of "+str(colorNumber)+" colors.\n This may take a while.",  button1 = scribus.BUTTON_OK)
290
    scribus.statusMessage("Drawing color fields...")
291
    stepCompleted=0
292
    #disable redrawing for better performance
293
    scribus.setRedraw(False)
294
    for color in colorList:
295
        if (vSpaceUsedByField * (colorFieldCounter+1)) <= vSpaceAvailable:
296
            # when there is enought space left draw a color field...
13058 subik 297
 
12781 subik 298
            #calculate Position for new colorField
299
            h=leftMargin
300
            v=topMargin + (vSpaceUsedByField * colorFieldCounter)+HEADERSIZE
301
            #draw the colorField
13058 subik 302
            drawColor(color, h, v,  colorFieldWidth, COLOR_FIELD_HEIGHT)
12781 subik 303
            colorFieldCounter = colorFieldCounter+1
304
            #update progressbar
305
            stepCompleted = stepCompleted+1
306
            scribus.progressSet(stepCompleted)
307
        else:
308
            #not enough space? create a new page!
309
            createPage()
310
            #reset the colorFieldCounter to '0' since we created a new page
311
            colorFieldCounter = 0
312
            h=leftMargin
313
            v=topMargin + (vSpaceUsedByField * colorFieldCounter)+HEADERSIZE
13058 subik 314
            drawColor(color, h, v,  colorFieldWidth, COLOR_FIELD_HEIGHT)
12781 subik 315
            colorFieldCounter = colorFieldCounter+1
316
 
317
            #update progressbar
318
            stepCompleted = stepCompleted+1
319
            scribus.progressSet(stepCompleted)
13058 subik 320
 
12781 subik 321
    #make shure pages are redrawn
322
    scribus.setRedraw(True)
323
 
324
 
325
def main(argv):
326
    """just invokes createChart() and displays a message after the chart is finished."""
327
    createChart()
13055 subik 328
    scribus.messageBox("ColorChart Script by Sebastian Stetter", "Your chart has been created, but not saved, yet!\nThanks for using ColorChart and Scribus!")
12781 subik 329
 
330
 
331
def main_wrapper(argv):
332
    """The main_wrapper() function disables redrawing, sets a sensible generic
333
    status bar message, and optionally sets up the progress bar. It then runs
334
    the main() function. Once everything finishes it cleans up after the main()
335
    function, making sure everything is sane before the script terminates."""
336
    try:
337
        scribus.statusMessage("Creating color chart...")
338
        scribus.progressReset()
339
        main(argv)
340
    finally:
341
        # Exit neatly even if the script terminated with an exception,
342
        # so we leave the progress bar and status bar blank and make sure
343
        # drawing is enabled.
344
        if scribus.haveDoc():
345
            scribus.setRedraw(True)
346
        scribus.statusMessage("")
347
        scribus.progressReset()
348
 
349
# This code detects if the script is being run as a script, or imported as a module.
350
# It only runs main() if being run as a script. This permits you to import your script
351
# and control it manually for debugging.
352
if __name__ == '__main__':
353
    main_wrapper(sys.argv)