Debian Codegraph @

plugin/gtk3/widget/miraclepainter.rb

raw symbols SCIP
1 # -*- coding: utf-8 -*-
2
3 require 'mui/cairo_icon_over_button'
4 require 'mui/cairo_textselector'
5 require 'mui/cairo_sub_parts_helper'
6 require 'mui/cairo_replyviewer'
7 require 'mui/cairo_sub_parts_favorite'
8 require 'mui/cairo_sub_parts_share'
9 require 'mui/cairo_sub_parts_quote'
10 require 'mui/cairo_markup_generator'
11 require 'mui/cairo_special_edge'
12 require 'mui/gtk_photo_pixbuf'
13
14 # Diva::Modelを表示するためのGtk::ListBoxRow。
15 # 名前は言いたかっただけ。クラス名まで全てはつね色に染めて♪
16 class Plugin::Gtk3::MiraclePainter < Gtk::ListBoxRow
17 # * カスタムwidgetの実装
18 # https://developer.gnome.org/gtkmm-tutorial/stable/sec-custom-widgets.html.en
19 # * height-for-widthの実装
20 # https://developer.gnome.org/gtk3/stable/GtkWidget.html#GtkWidget.description
21
22 class Rect
23 extend Memoist
24 attr_reader :x, :y, :width, :height
25
26 def initialize(x, y, width, height)
27 @x, @y, @width, @height = x, y, width, height
28 end
29
30 def point_in?(x, y)
31 left <= x and x <= right and top <= y and y <= bottom
32 end
33
34 def bottom
35 y + height
36 end
37
38 def right
39 x + width
40 end
41
42 alias :left :x
43 alias :top :y
44 end
45
46 ICON_SIZE = [48, 48].freeze # [width, height]
47 MARGIN = 2 # margin for icon, etc
48 SPACING = 2 # spacing between mainparts and subparts
49 DEPTH = Gdk::Visual.system.depth # color depth
50 VERBOSE = false # for debug
51
52 extend Gem::Deprecate
53
54 type_register
55
56 signal_new :clicked, GLib::Signal::RUN_FIRST | GLib::Signal::ACTION, nil, nil, Gdk::EventButton
57
58 signal_new :click, GLib::Signal::RUN_FIRST | GLib::Signal::ACTION, nil, nil, Gdk::EventButton, Integer, Integer # 互換性
59 signal_new :expose_event, GLib::Signal::RUN_FIRST, nil, nil # 互換性
60
61 include Gdk::IconOverButton
62 include Gdk::TextSelector
63 include Gdk::SubPartsHelper
64 include Gdk::MarkupGenerator
65
66 WHITE = [1.0, 1.0, 1.0].freeze
67 BLACK = [0.0, 0.0, 0.0].freeze
68 NUMERONYM_MATCHER = /[a-zA-Z]{4,}/
69 NUMERONYM_CONVERTER = ->(r) { "#{r[0]}#{r.size - 2}#{r[-1]}" }
70
71 attr_reader :model
72 alias message model
73 # TODO: gtk3 deprecate :message
74 # deprecate :message, :model, 2019, 10
75
76 # TODO: gtk3 adjust size
77 WIDTH_MIN = 100 # minimum width
78 WIDTH_NAT = 250 # natural width
79
80 # :nodoc:
81 def score
82 @score ||= Plugin[:gtk3].score_of(model)
83 end
84
85 def initialize(model)
86 super()
87
88 @model = model
89 @mouse_in_row = false
90
91 # This widget create _Gdk::Window_ itself on _realize_.
92 self.has_window = true
93 self.redraw_on_allocate = true
94 style_context.add_class 'miraclepainter'
95 end
96
97 def message=(newer)
98 if newer.uri != message.uri
99 raise 'Old message %{old} and new message %{new} are different.' % {
100 new: newer.uri,
101 old: message.uri
102 }
103 end
104 @model = newer
105 queue_draw
106 end
107
108 # override virtual function Gtk::Widget.get_request_mode
109 def virtual_do_get_request_mode
110 notice 'MiraclePainter#get_request_mode' if VERBOSE
111
112 Gtk::SizeRequestMode::HEIGHT_FOR_WIDTH
113 end
114
115 # override virtual function Gtk::Widget.get_preferred_width
116 def virtual_do_get_preferred_width
117 notice 'MiraclePainter#get_preferred_width' if VERBOSE
118
119 [WIDTH_MIN, WIDTH_NAT]
120 end
121
122 # override virtual function Gtk::Widget.get_preferred_height_for_width
123 def virtual_do_get_preferred_height_for_width(width)
124 notice "MiraclePainter#get_preferred_height_for_width(width=#{width})" if VERBOSE
125
126 @width = width
127 height = forecast_height
128 [height, height] # minimum, natural
129 rescue Exception => exception # rubocop:disable Lint/RescueException
130 Gtk.exception = exception
131 [0, 0]
132 end
133
134 # connect signal Gtk::Widget*parent_set
135 def signal_do_parent_set(prev_parent)
136 if VERBOSE
137 notice "#{self}*parent_set(prev_parent=#{prev_parent.inspect}) " \
138 "parent=#{parent.inspect}"
139 end
140
141 @width = allocated_width
142 end
143
144 # connect signal Gtk::Widget*size_allocate
145 # リサイズ時に呼ばれる
146 # signalの発行順序: size_allocate > realize > draw
147 def signal_do_size_allocate(rect)
148 notice "#{self}*size_allocate(rect=#{rect})" if VERBOSE
149
150 self.allocation = rect
151 x, y, w, h = rect.x, rect.y, rect.width, rect.height
152 if realized?
153 window.move_resize(x, y, w, h)
154 end
155 @width = w
156 end
157
158 # connect signal Gtk::Widget*realize
159 def signal_do_realize
160 notice "#{self}*realize" if VERBOSE
161
162 attr = Gdk::WindowAttr.new(
163 allocation.width,
164 allocation.height,
165 :input_output,
166 :child
167 )
168 attr.x = allocation.x
169 attr.y = allocation.y
170 attr.visual = visual
171 attr.event_mask = Gdk::EventMask::BUTTON_PRESS_MASK |
172 Gdk::EventMask::BUTTON_RELEASE_MASK |
173 Gdk::EventMask::POINTER_MOTION_MASK |
174 Gdk::EventMask::ENTER_NOTIFY_MASK |
175 Gdk::EventMask::LEAVE_NOTIFY_MASK |
176 Gdk::EventMask::TOUCH_MASK
177
178 self.window = Gdk::Window.new(
179 parent_window,
180 attr,
181 Gdk::WindowAttributesType::X | Gdk::WindowAttributesType::Y | Gdk::WindowAttributesType::VISUAL
182 )
183 register_window(window)
184
185 self.realized = true
186 end
187
188 # connect signal Gtk::Widget*unrealize
189 def signal_do_unrealize
190 notice "#{self}*unrealize" if VERBOSE
191
192 unregister_window window
193 window.destroy
194 self.realized = false
195 end
196
197 # connect signal Gtk::Widget*map
198 def singla_do_map
199 super
200
201 window.show
202 end
203
204 # connect signal Gtk::Widget*unmap
205 def signal_do_unmap
206 super
207
208 window.hide
209 end
210
211 # connect signal Gtk::Widget*draw
212 def signal_do_draw(context)
213 # context => Cairo::Context
214 notice "#{self}*draw(context)" if VERBOSE
215 x, y, w, h = allocation.x, allocation.y, allocation.width, allocation.height
216
217 Gtk.render_frame style_context, context, x, y, w, h
218 Gtk.render_background style_context, context, x, y, w, h
219
220 render_to_context(context)
221 # 描画してみたら確保されていた描画域の高さに過不足があった
222 if forecast_height != allocation.height
223 queue_resize
224 end
225 true # stop propagation
226 rescue Exception => exception # rubocop:disable Lint/RescueException
227 Gtk.exception = exception
228 true # stop propagation
229 end
230
231 # connect signal Gtk::Widget*clicked
232 def signal_do_clicked(event)
233 case event.button
234 when 1
235 iob_clicked(event.x, event.y)
236 unless textselector_range
237 index = main_pos_to_index(event.x, event.y)
238 if index
239 clicked_note = score.find do |note|
240 index -= if UserConfig[:miraclepainter_expand_custom_emoji] && note.respond_to?(:inline_photo)
241 # 1 -> 置換された絵文字の文字長
242 1
243 else
244 note.description.size
245 end
246 index < 0
247 end
248 Plugin.call(:open, clicked_note) if clickable?(clicked_note)
249 end
250 end
251 end
252 end
253
254 # 互換性
255 def signal_do_click(_, _, _); end
256
257 def signal_do_button_press_event(event)
258 if event.triggers_context_menu
259 timeline = get_ancestor(Plugin::Gtk3::Timeline)
260 unless timeline.selected_rows.include?(self)
261 timeline.unselect_all
262 timeline.select_row(self)
263 end
264 popup_menu(event)
265 return true
266 end
267
268 if event.button == 1
269 textselector_press(*main_pos_to_index_forclick(event.x, event.y)[1..2])
270 end
271 false # propagate event
272 end
273
274 def signal_do_button_release_event(event)
275 if event.button == 1
276 textselector_release(
277 *main_pos_to_index_forclick(event.x, event.y)[1..2]
278 )
279 end
280 if @mouse_in_row || event.event_type == Gdk::EventType::TOUCH_END
281 signal_emit(:clicked, event)
282 signal_emit(:click, event, event.x, event.y) # 互換性
283 end
284 false # propagate event
285 end
286
287 def signal_do_motion_notify_event(event)
288 point_moved_main_icon(event.x, event.y)
289 textselector_select(*main_pos_to_index_forclick(event.x, event.y)[1..2])
290
291 # change cursor shape
292 window.cursor = Gdk::Cursor.new(cursor_name_of(event.x, event.y))
293 false # propagate event
294 end
295
296 def signal_do_enter_notify_event(_)
297 @mouse_in_row = true
298 false # propagate event
299 end
300
301 def signal_do_leave_notify_event(_)
302 @mouse_in_row = false
303 iob_main_leave
304 textselector_release
305 # restore cursor shape
306 window.cursor = nil
307 false # propagate event
308 end
309
310 def signal_do_focus_in_event(event)
311 get_ancestor(Plugin::Gtk3::Timeline).active
312 end
313
314 def signal_do_key_press_event(event)
315 timeline = get_ancestor(Plugin::Gtk3::Timeline)
316 timeline.keypress(Gtk.keyname([event.keyval, event.state]))
317 end
318
319 # for keybindings (Shift-F10 or Menu)
320 # see https://developer.gnome.org/gtk3/stable/gtk-migrating-checklist.html#checklist-popup-menu
321 def signal_do_popup_menu
322 popup_menu(nil)
323 true
324 end
325
326 def iob_icon_pixbuf
327 [['reply.png'.freeze, message.user.verified? ? 'verified.png' : 'etc.png'],
328 [if message.user.protected? then 'protected.png'.freeze else 'retweet.png'.freeze end,
329 message.favorite? ? 'unfav.png'.freeze : 'fav.png'.freeze]]
330 end
331
332 def iob_icon_pixbuf_off
333 world, = Plugin.filtering(:world_current, nil)
334 [[(UserConfig[:show_replied_icon] and message.mentioned_by_me? and 'reply.png'.freeze),
335 UserConfig[:show_verified_icon] && message.user.verified? && 'verified.png'],
336 [if UserConfig[:show_protected_icon] && message.user.protected?
337 'protected.png'.freeze
338 elsif Plugin[:miracle_painter].shared?(message, world)
339 'retweet.png'.freeze end,
340 message.favorite? ? 'unfav.png'.freeze : nil]]
341 end
342
343 def iob_reply_clicked
344 get_ancestor(Plugin::Gtk3::Timeline).imaginary.create_reply_postbox(message)
345 end
346
347 def iob_retweet_clicked
348 world, = Plugin.filtering(:world_current, nil)
349 if Plugin[:miracle_painter].shared?(message, world)
350 retweet = message.retweeted_statuses.find(&:from_me?)
351 retweet&.destroy
352 else
353 Plugin[:miracle_painter].share(message, world)
354 end
355 end
356
357 def iob_fav_clicked
358 message.favorite(!message.favorite?)
359 end
360
361 def iob_etc_clicked; end
362
363 # つぶやきの左上座標から、クリックされた文字のインデックスを返す
364 def main_pos_to_index(x, y)
365 x -= main_text_rect.x
366 y -= main_text_rect.y
367 inside, byte, = *main_message.xy_to_index(x * Pango::SCALE, y * Pango::SCALE)
368 main_message.text.get_index_from_byte(byte) if inside
369 end
370
371 def main_pos_to_index_forclick(x, y)
372 x -= main_text_rect.x
373 y -= main_text_rect.y
374 result = main_message.xy_to_index(x * Pango::SCALE, y * Pango::SCALE)
375 result[1] = main_message.text.get_index_from_byte(result[1])
376 result
377 end
378
379 @@font_description = Hash.new { |h, k| h[k] = {} } # {scale => {font => FontDescription}}
380 def font_description(font)
381 @@font_description[Gdk.scale(0xffff)][font] ||=
382 Pango::FontDescription.new(font).tap { |fd| fd.size = Gdk.scale(fd.size) }
383 end
384
385 def forecast_height
386 mainpart_height + SPACING + subparts_height
387 end
388
389 def mainpart_height
390 [
391 forecast_main_message_height + forecast_header_left_height,
392 Gdk.scale(ICON_SIZE[1])
393 ].max + MARGIN
394 end
395
396 def forecast_main_message_height
397 @main_message_height || main_message.pixel_size[1]
398 end
399
400 def forecast_header_left_height
401 @header_left_height || header_left.pixel_size[1]
402 end
403
404 # 互換性
405 def reset_height
406 queue_resize
407 end
408 deprecate :reset_height, :queue_resize, 2020, 7
409
410 # 互換性
411 def on_modify
412 queue_resize
413 end
414 deprecate :on_modify, :queue_resize, 2020, 7
415
416 def inspect
417 "MP(#{model.description[0, 5].gsub("\n", ' ').inspect})"
418 end
419 alias to_s inspect
420
421 private
422
423 def popup_menu(event)
424 get_ancestor(Plugin::Gtk3::Timeline).popup_menu(event)
425 end
426
427 def main_icon_rect
428 @main_icon_rect ||= Rect.new(MARGIN, MARGIN, *ICON_SIZE.map(&Gdk.method(:scale)))
429 end
430
431 # 本文(model#description)
432 def main_text_rect
433 Rect.new(
434 Gdk.scale(ICON_SIZE[0]) + 2 * MARGIN,
435 header_text_rect.height,
436 text_width,
437 0
438 )
439 end
440
441 def header_text_rect
442 Rect.new(
443 Gdk.scale(ICON_SIZE[0]) + 2 * MARGIN,
444 MARGIN,
445 text_width,
446 forecast_header_left_height
447 )
448 end
449
450 def text_width
451 @width - Gdk.scale(ICON_SIZE[0]) - 4 * MARGIN
452 end
453
454 def main_message_context
455 context = @main_messsage_context ||= PangoCairo::FontMap.default.create_context
456
457 Plugin.filtering(:message_font, message, nil)&.last&.then do |font|
458 context.set_font_description(font_description(font))
459 end
460
461 context
462 end
463
464 # 本文のための Pango::Layout のインスタンスを返す
465 def main_message(context=nil)
466 layout = Pango::Layout.new(main_message_context)
467 layout.text = plain_description
468 layout.width = main_text_rect.width * Pango::SCALE
469 layout.attributes = textselector_attr_list(
470 description_attr_list(emoji_height: layout.context.font_description.forecast_font_size, pango_context: layout.context)
471 )
472 layout.wrap = Pango::WrapMode::CHAR
473 if context
474 context.set_source_rgb(*htmlcolor2gdk(Plugin.filtering(:message_font_color, message, nil).last || BLACK))
475
476 layout.context&.set_shape_renderer do |c, shape, _|
477 photo = shape.data
478 next layout unless photo
479 draw_area = layout.index_to_pos(shape.start_index)
480 width = draw_area.width / Pango::SCALE
481 height = draw_area.height / Pango::SCALE
482 pixbuf = photo.load_pixbuf(width:, height:) do
483 queue_draw
484 end
485 x = draw_area.x / Pango::SCALE
486 y = draw_area.y / Pango::SCALE
487 c.translate(x, y)
488 c.set_source_pixbuf(pixbuf)
489 c.rectangle(0, 0, width, height)
490 c.fill
491 end
492 @main_message_height = layout.pixel_size[1]
493 end
494 layout
495 end
496
497 def header_left_context
498 context = @main_messsage_context ||= PangoCairo::FontMap.default.create_context
499
500 Plugin.filtering(:message_header_left_font, message, nil)&.last&.then do |font|
501 context.set_font_description(font_description(font))
502 end
503
504 context
505 end
506
507 # ヘッダ(左)のための Pango::Layout のインスタンスを返す
508 def header_left(context=nil)
509 attr_list, text = header_left_markup
510 context&.set_source_rgb(*htmlcolor2gdk(Plugin.filtering(:message_header_left_font_color, message, nil).last || BLACK))
511 Pango::Layout.new(header_left_context).tap do |layout|
512 layout.attributes = attr_list
513 layout.text = text
514 if context
515 @header_left_height = layout.pixel_size[1]
516 end
517 end
518 end
519
520 def header_left_markup
521 user = message.user
522 if user.respond_to?(:idname)
523 Pango.parse_markup("<b>#{Pango.escape(rinsuki_abbr(user))}</b> #{Pango.escape(user.name || '')}")
524 else
525 Pango.parse_markup(Pango.escape(user.name || ''))
526 end
527 end
528
529 def rinsuki_abbr(user)
530 return user.idname unless UserConfig[:idname_abbr]
531 prefix, domain = user.idname.split('@', 2)
532 if domain
533 "#{prefix}@#{domain.gsub(NUMERONYM_MATCHER, &NUMERONYM_CONVERTER)}"
534 else
535 user.idname
536 end
537 end
538
539 # ヘッダ(右)のための Pango::Layout のインスタンスを返す
540 def header_right(context)
541 hms = timestamp_label
542 attr_list, text = Pango.parse_markup(hms)
543 layout = context.create_pango_layout
544 layout.attributes = attr_list
545 font = Plugin.filtering(:message_header_right_font, message, nil).last
546 layout.font_description = font_description(font) if font
547 layout.text = text
548 layout.alignment = Pango::Alignment::RIGHT
549 layout
550 end
551
552 def timestamp_label
553 now = Time.now
554 if message.created.year == now.year && message.created.month == now.month && message.created.day == now.day
555 Pango.escape(message.created.strftime('%H:%M:%S'))
556 else
557 Pango.escape(message.created.strftime('%Y/%m/%d %H:%M:%S'))
558 end
559 end
560
561 # アイコンのpixbufを返す
562 def main_icon
563 w, h = ICON_SIZE
564 @main_icon ||= model.user.icon.load_pixbuf(width: Gdk.scale(w), height: Gdk.scale(h)) do |pb|
565 @main_icon = pb
566 queue_draw
567 end
568 end
569
570 # 背景色を返す
571 def get_backgroundcolor
572 color = Plugin.filtering(
573 selected? ? :message_selected_bg_color : :message_bg_color,
574 model, nil
575 ).last
576 htmlcolor2gdk(color || WHITE)
577 end
578
579 # GTK2のGtk::ColorとGTK3のGdk::RGBAをRGBの_Float_値に変換する
580 def htmlcolor2gdk(color)
581 r, g, b = color
582 [r.fdiv(65536), g.fdiv(65536), b.fdiv(65536)].freeze
583 end
584
585 # Graphic Context にパーツを描画
586 def render_to_context(context)
587 render_background(context)
588 render_main_icon(context)
589 render_main_text(context)
590 render_parts(context)
591 end
592
593 def render_background(context)
594 context.save do
595 context.set_source_rgb(*get_backgroundcolor)
596 context.rectangle(0, 0, allocation.width, allocation.height)
597 context.fill
598 if Gtk.konami
599 context.save do
600 context.translate(width - 48, height - 54)
601 context.set_source_pixbuf(Gtk.konami_image)
602 context.paint
603 end
604 end
605 end
606 end
607
608 def render_main_icon(context)
609 case Plugin.filtering(:main_icon_form, :square)[0]
610 when :aspectframe
611 render_main_icon_aspectframe(context)
612 else
613 render_main_icon_square(context)
614 end
615 end
616
617 def render_main_icon_square(context)
618 context.save do
619 context.translate(main_icon_rect.x, main_icon_rect.y)
620 context.set_source_pixbuf(main_icon)
621 context.paint
622 end
623 unless message.system?
624 render_icon_over_button(context) end
625 end
626
627 def render_main_icon_aspectframe(context)
628 context.save do
629 context.save do
630 context.translate(main_icon_rect.x, main_icon_rect.y + Gdk.scale(ICON_SIZE[1]) * 13 / 14)
631 w = Gdk.scale(ICON_SIZE[0])
632 context.set_source_pixbuf(
633 gb_foot.load_pixbuf(width: w, height: 9 * w / 20) { queue_draw }
634 )
635 context.paint
636 end
637 context.translate(main_icon_rect.x, main_icon_rect.y)
638 context.append_path(Cairo::SpecialEdge.path(*ICON_SIZE.map(&Gdk.method(:scale))))
639 context.set_source_rgb(0, 0, 0)
640 context.stroke
641 context.append_path(Cairo::SpecialEdge.path(*ICON_SIZE.map(&Gdk.method(:scale))))
642 context.set_source_pixbuf(main_icon)
643 context.fill
644 end
645 unless message.system?
646 render_icon_over_button(context) end
647 end
648
649 def render_main_text(context)
650 context.save do # ヘッダ
651 context.translate(header_text_rect.x, header_text_rect.y)
652 context.set_source_rgb(0, 0, 0)
653 hl_layout = header_left(context)
654 context.show_pango_layout(hl_layout)
655 hr_layout = header_right(context)
656 hr_color = htmlcolor2gdk(Plugin.filtering(:message_header_right_font_color, message, nil).last || BLACK)
657
658 context.save do
659 context.translate(header_text_rect.width - (hr_layout.size[0] / Pango::SCALE), 0)
660 if (hl_layout.size[0] / Pango::SCALE) > (header_text_rect.width - (hr_layout.size[0] / Pango::SCALE) - 20)
661 r, g, b = get_backgroundcolor
662 grad = Cairo::LinearPattern.new(-20, 0, hr_layout.size[0] / Pango::SCALE + 20, 0)
663 grad.add_color_stop_rgba(0.0, r, g, b, 0.0)
664 grad.add_color_stop_rgba(20.0 / (hr_layout.size[0] / Pango::SCALE + 20), r, g, b, 1.0)
665 grad.add_color_stop_rgba(1.0, r, g, b, 1.0)
666 context.rectangle(-20, 0, hr_layout.size[0] / Pango::SCALE + 20, hr_layout.size[1] / Pango::SCALE)
667 context.set_source(grad)
668 context.fill
669 end
670 context.set_source_rgb(*hr_color)
671 context.show_pango_layout(hr_layout)
672 end
673 end
674 context.save do
675 context.translate(main_text_rect.x, main_text_rect.y)
676 context.show_pango_layout(main_message(context))
677 end
678 end
679
680 # このMiraclePainterの(x , y)にマウスポインタがある時に表示すべきカーソルの名前を返す。
681 # ==== Args
682 # [x] x座標(Integer)
683 # [y] y座標(Integer)
684 # ==== Return
685 # [String] カーソルの名前
686 def cursor_name_of(x, y)
687 index = main_pos_to_index(x, y)
688 if index # the cursor is placed on text
689 pointed_note = score.find do |note|
690 index -= if UserConfig[:miraclepainter_expand_custom_emoji] && note.respond_to?(:inline_photo)
691 # 1 -> 置換された絵文字の文字長
692 1
693 else
694 note.description.size
695 end
696 index < 0
697 end
698 if clickable?(pointed_note)
699 # the cursor is placed on link
700 'hand2'
701 else
702 'text'
703 end
704 else
705 'default'
706 end
707 end
708
709 def gb_foot
710 self.class.gb_foot
711 end
712
713 class << self
714 def gb_foot
715 @gb_foot ||= Plugin.collect(:photo_filter, Cairo::SpecialEdge::FOOTER_URL, Pluggaloid::COLLECT).first
716 end
717 end
718 end