summaryrefslogtreecommitdiff
path: root/rt/share/html/Admin/Tools/Theme.html
blob: e8b237d38d78a029a68afd851ab91bc8fb000c15 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
%# BEGIN BPS TAGGED BLOCK {{{
%#
%# COPYRIGHT:
%#
%# This software is Copyright (c) 1996-2017 Best Practical Solutions, LLC
%#                                          <sales@bestpractical.com>
%#
%# (Except where explicitly superseded by other copyright notices)
%#
%#
%# LICENSE:
%#
%# This work is made available to you under the terms of Version 2 of
%# the GNU General Public License. A copy of that license should have
%# been provided with this software, but in any event can be snarfed
%# from www.gnu.org.
%#
%# This work is distributed in the hope that it will be useful, but
%# WITHOUT ANY WARRANTY; without even the implied warranty of
%# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
%# General Public License for more details.
%#
%# You should have received a copy of the GNU General Public License
%# along with this program; if not, write to the Free Software
%# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
%# 02110-1301 or visit their web page on the internet at
%# http://www.gnu.org/licenses/old-licenses/gpl-2.0.html.
%#
%#
%# CONTRIBUTION SUBMISSION POLICY:
%#
%# (The following paragraph is not intended to limit the rights granted
%# to you to modify and distribute this software under the terms of
%# the GNU General Public License and is only of importance to you if
%# you choose to contribute your changes and enhancements to the
%# community by submitting them to Best Practical Solutions, LLC.)
%#
%# By intentionally submitting any modifications, corrections or
%# derivatives to this work, or any other work intended for use with
%# Request Tracker, to Best Practical Solutions, LLC, you confirm that
%# you are the copyright holder for those contributions and you grant
%# Best Practical Solutions,  LLC a nonexclusive, worldwide, irrevocable,
%# royalty-free, perpetual, license to use, copy, create derivative
%# works based on those contributions, and sublicense and distribute
%# those contributions and any derivatives thereof.
%#
%# END BPS TAGGED BLOCK }}}
<& /Admin/Elements/Header,
    Title => loc("Theme"),
&>
<& /Elements/Tabs &>
<& /Elements/ListActions, actions => \@results &>

<script type="text/javascript" src="<%RT->Config->Get('WebPath')%>/static/js/farbtastic.js"></script>

<div id="simple-customize">
<div id="upload-logo">
  <h2>Logo</h2>
  <& /Elements/Logo, id => 'logo-theme-editor', ShowName => 0 &>
  <form method="POST" enctype="multipart/form-data">
    <label for="logo-upload"><&|/l&>Upload a new logo</&>:</label>
    <input type="file" name="logo-upload" id="logo-upload" /><br />
    <div class="gd-support">
% if ($valid_image_types) {
    <&|/l, $valid_image_types &>Your system supports automatic color suggestions for: [_1]</&>
% } else {
    <&|/l&>GD is disabled or not installed. You can upload an image, but you won't get automatic color suggestions.</&>
% }
    </div>
    <input name="reset_logo" value="<&|/l&>Reset to default RT Logo</&>" type="submit" />
    <input type="submit" value="<&|/l&>Upload</&>" />
  </form>
</div>

<div id="customize-theme">
  <h2><&|/l&>Customize the RT theme</&></h2>
  <ol>
    <li>
      <label for="section"><&|/l&>Select a section</&>:</label>
      <select id="section"></select>
    </li>
    <li>
      <div class="description">
        <&|/l&>Select a color for the section</&>:
        <div id="logo-picker-hint" style="display: none;">
          <&|/l&>You can also click on the logo above to get colors!</&>
        </div>
      </div>
% if ($colors) {
<div class="primary-colors">
%   for (@$colors) {
%     my $fg = $_->{l} >= $text_threshold ? 'black' : 'white';
<button type="button" class="color-template"
        style="background-color: rgb(<% $_->{c} %>); color: <% $fg %>;">
  <&|/l&>Text</&>
</button>
%   }
</div>
% }
      <div id="color-picker"></div>
      <canvas id="logo-color-picker" title="<&|/l&>Click to choose a color</&>"></canvas>
    </li>
  </ol>
</div>
</div>

<div id="custom-css">
  <h2><&|/l&>Custom CSS (Advanced)</&></h2>

  <form method="POST">
    <textarea rows=20 id="user_css" name="user_css" wrap="off"><% $user_css %></textarea><br />
    <input id="try" type="button" class="button" value="<&|/l&>Try</&>" />
    <input id="reset" type="reset" value="<&|/l&>Reset</&>" type="submit" />
    <input name="reset_css" value="<&|/l&>Reset to default RT Theme</&>" type="submit" />
    <input value="<&|/l&>Save</&>" type="submit" />
  </form>
</div>

<%ONCE>
my @sections = (
    ['Page'         => ['body', 'div#body']],
    ['Menu bar'     => ['div#quickbar', '#main-navigation #app-nav.sf-shadow > li, #main-navigation #app-nav.sf-shadow > li > a, #prefs-menu > li, #prefs-menu > li > a, #logo .rtname']],
    ['Title bar'    => ['div#header']],
    ['Page title'   => ['div#header h1']],
    ['Page content' => ['div#body']],
    ['Buttons'      => ['input[type="reset"], input[type="submit"], input[class="button"]']],
    ['Button hover' => ['input[type="reset"]:hover, input[type="submit"]:hover, input[class="button"]:hover']],
);
</%ONCE>
<script type="text/javascript">
var section_css_mapping = <% JSON(\@sections) |n%>;

jQuery(function($) {

    jQuery.each(section_css_mapping, function(i,v){
        $('select#section').append($("<option/>")
                           .attr('value', v[0])
                           .text(v[0]));
    });

    function update_sitecss(text) {
        if (!text)
            text = $('#user_css').val();

        // IE 8 doesn't let us update the innerHTML of <style> tags (with jQuery.text())
        // see: http://stackoverflow.com/questions/2692770/style-style-textcss-appendtohead-does-not-work-in-ie/2692861#2692861
        $("style#sitecss").remove();
        $("<style id='sitecss' type='text/css' media='all'>" + text + "</style>").appendTo('head');
    }

    update_sitecss();
    $('#try').click(function() {
        update_sitecss();
    });

    $('#reset').click(function() {
        setTimeout(function() {
            update_sitecss();
        }, 1000);
    });

    function change_color(bg, fg) {
      var section = $('select#section').val();

      var applying = jQuery.grep(section_css_mapping, function(a){ return a[0] == section })[0][1];
      var css = $('#user_css').val();
      if (applying) {
          var specials = new RegExp("([.*+?|()\\[\\]{}\\\\])", "g");
          for (var name in applying) {
              var selector = (applying[name]).replace(specials, "\\$1");
              var rule = new RegExp('^'+selector+'\\s*\{.*?\}', "m");
              var newcss = "background: " + bg;

              /* Don't set the text color on <body> as it affects too much */
              if (applying[name] != "body")
                  newcss += "; color: " + fg;

              /* Kill the border on the quickbar if we're styling it */
              if (applying[name].match(/quickbar/))
                  newcss += "; border: none;"

              /* Page title's text color is the selected color */
              if (applying[name].match(/h1/))
                  newcss = "color: " + bg;

              /* Nav doesn't need a background, but it wants text color */
              if (applying[name].match(/#main-navigation/))
                  newcss = "color: " + fg;

              css = css.replace(rule, applying[name]+" { "+newcss+" }");
          }
      }
      $('#user_css').val(css);
      update_sitecss(css);
    }

    $('#color-picker').farbtastic(function(color){ change_color(color, this.hsl[2] > <% $text_threshold %> ? '#000' : '#fff') });

    $('button.color-template').click(function() {
      change_color($(this).css('background-color'), $(this).css('color'));
  });

    // Setup the canvas color picker
    $("#logo-theme-editor img").load(function() {
        var logo      = $(this);
        var canvas    = $("#logo-color-picker");
        var el_canvas = canvas.get(0);

        if (!el_canvas.getContext) return;

        var context      = el_canvas.getContext("2d");
        el_canvas.width  = logo.width();
        el_canvas.height = logo.height();
        context.drawImage(logo.get(0), 0, 0);

        logo.hide().after(canvas);
        canvas.show().click(function(ev) {
            ev.preventDefault();
            var R = 0,
                G = 1,
                B = 2,
                A = 3;
            var pixel = this.getContext("2d").getImageData(ev.offsetX, ev.offsetY, 1, 1).data;
            // Farbtastic expects values in the range of 0..1
            var rgba  = $.makeArray(pixel).map(function(v,i) { return v / 255 });
            var wheel = $.farbtastic("#color-picker");
            wheel.setHSL( wheel.RGBToHSL( rgba.slice(R,A) ) );
            // XXX TODO factor in the alpha channel too
        });
        $('#logo-picker-hint').show();
    });
});
</script>
<%INIT>
unless ($session{'CurrentUser'}->HasRight( Object=> RT->System, Right => 'SuperUser')) {
    Abort(loc('This feature is only available to system administrators.'));
}

use Digest::MD5 'md5_hex';

my $text_threshold = 0.6;
my @results;
my $imgdata;

my $colors;
my $valid_image_types;
if (not RT->Config->Get('DisableGD') and Convert::Color->require) {
    require GD;

    # Always find out what GD can read...
    my %gd_can;
    for my $type (qw(Png Jpeg Gif)) {
        $gd_can{$type}++ if GD::Image->can("newFrom${type}Data");
    }
    $valid_image_types = join(", ", map { uc } sort { lc $a cmp lc $b } keys %gd_can);
}

my $analyze_img = sub {
    return undef unless $valid_image_types;

    my $imgdata = shift;
    return undef unless $imgdata;

    # ...but only analyze the image if we have data
    my $img = GD::Image->new($imgdata);
    unless ($img) {
        # This has to be one damn long line because the loc() needs to be
        # source parsed correctly.
        push @results, loc("Automatically suggested theme colors aren't available for your image. This might be because you uploaded an image type that your installed version of GD doesn't support. Supported types are: [_1]. You can recompile libgd and GD.pm to include support for other image types.", $valid_image_types);
        return undef;
    }

    my %colors;

    my @wsamples;
    my @hsamples;
    if ($img->width > 200) {
        @wsamples = map { int($img->width*($_/200)) } (0..199);
    } else {
        @wsamples = ( 0 .. $img->width - 1 );
    }
    if ($img->height > 200) {
        @hsamples = map { int($img->height*($_/200)) } (0..199);
    } else {
        @hsamples = ( 0 .. $img->height - 1 );
    }
    for my $i (@wsamples) {
        for my $j (@hsamples) {
            my @color = $img->rgb( $img->getPixel($i,$j) );
            my $hsl = Convert::Color->new('rgb:'.join(',',map { $_ / 255 } @color))->convert_to('hsl');
            my $c = join(',',@color);
            next if $hsl->lightness < 0.1;
            $colors{$c} ||= { h => $hsl->hue, s => $hsl->saturation, l => $hsl->lightness, cnt => 0, c => $c};
            $colors{$c}->{cnt}++;
        }
    }

    for (values %colors) {
        $_->{rank} = $_->{s} * $_->{cnt};
    }
    my @top5 = grep { defined and $_->{'l'} and $_->{'c'} }
                    (sort { $b->{rank} <=> $a->{rank} } values %colors)[0..5];
    return \@top5;
};

if (my $file_hash = _UploadedFile( 'logo-upload' )) {
    $colors = $analyze_img->($file_hash->{LargeContent});

    my $my_system = RT::System->new( $session{CurrentUser} );
    my ( $id, $msg ) = $my_system->SetAttribute(
        Name        => "UserLogo",
        Description => "User-provided logo",
        Content     => {
            type => $file_hash->{ContentType},
            data => $file_hash->{LargeContent},
            hash => md5_hex($file_hash->{LargeContent}),
            colors => $colors,
        },
    );

    push @results, loc("Unable to set UserLogo: [_1]", $msg) unless $id;

    $imgdata = $file_hash->{LargeContent};
}
elsif ($ARGS{'reset_logo'}) {
    RT->System->DeleteAttribute('UserLogo');
}
else {
    if (my $attr = RT->System->FirstAttribute('UserLogo')) {
        my $content = $attr->Content;
        if (ref($content) eq 'HASH') {
            $imgdata = $content->{data};
            $colors = $content->{colors};
            unless ($colors) {
                # No colors cached; attempt to generate them
                $colors = $content->{colors} = $analyze_img->($content->{data});
                if ($content->{colors}) {
                    # Found colors; update the attribute
                    RT->System->SetAttribute(
                        Name => "UserLogo",
                        Description => "User-provided logo",
                        Content => $content,
                    );
                }
            }
        }
        else {
            RT->System->DeleteAttribute('UserLogo');
        }
    }
}

if ($user_css) {
    if ($ARGS{'reset_css'}) {
        RT->System->DeleteAttribute('UserCSS');
        undef $user_css;
    }
    else {
        my ($id, $msg) = RT->System->SetAttribute( Name => "UserCSS",
                                                    Description => "User-provided css",
                                                    Content => $user_css );
        push @results, loc("Unable to set UserCSS: [_1]", $msg) unless $id;
    }
}

if (!$user_css) {
    my $attr = RT->System->FirstAttribute('UserCSS');
    $user_css = $attr ? $attr->Content : join(
        "\n\n" => map {
            join "\n" => "/* ". $_->[0] ." */",
                         map { "$_ {}" } @{$_->[1]}
        } @sections
    );
}
</%INIT>
<%ARGS>
$user_css => ''
</%ARGS>