Debian Codegraph @

core/skin.rb

raw symbols SCIP
1 # -*- coding: utf-8 -*-
2
3 require 'userconfig'
4 require 'plugin'
5
6 module Skin
7 class SkinError < RuntimeError; end
8 class FileNotFoundError < SkinError; end
9 class ModelNotFoundError < SkinError; end
10
11 def self.extended(klass)
12 klass.class_eval{ @get_path = ::TimeLimitedStorage.new(Integer, String, 60) }
13 end
14
15 extend self
16 extend Gem::Deprecate
17
18 SKIN_ROOT = File.join(CHIConfig::CONFROOT, "skin")
19 USER_SKIN = if :vanilla == UserConfig[:skin_dir]
20 nil
21 else
22 UserConfig[:skin_dir] end
23 AVAILABLE_EXTENSIONS = %w[svg png jpg jpeg].map{|ext| [ext.downcase, ext.upcase] }.flatten.freeze
24
25 def default_dir
26 @default_dir ||= File.join(__dir__, "skin", "data").freeze
27 end
28
29 def default_image
30 @default_image ||= File.join(default_dir, "notfound.png").freeze
31 end
32
33 def user_dir
34 if USER_SKIN
35 File.join(SKIN_ROOT, USER_SKIN)
36 else
37 nil
38 end
39 end
40
41 def path
42 user_dir || default_dir
43 end
44
45 # 現在のSkinにおける、 _filename_ の画像を示すPhoto Modelを取得する
46 # ==== Args
47 # [filename] 画像ファイル名
48 # [fallback_dirs] スキンディレクトリのリスト
49 # ==== Return
50 # [Diva::Mixin::PhotoMixin] 画像
51 # ==== Raises
52 # [Skin::FileNotFoundError] 画像 _filename_ が見つからなかった時
53 def photo(filename, fallback_dirs=[])
54 result = Plugin::Skin::Image[get_path(filename, fallback_dirs)]
55 raise FileNotFoundError, "File `#{filename}' does not exists." unless result
56 result
57 end
58 alias :[] :photo
59
60 def get_path(filename, fallback_dirs = [])
61 @get_path[filename.hash ^ fallback_dirs.hash] ||= get_path_nocache(filename, fallback_dirs)
62 end
63 alias :get :get_path
64 deprecate :get, "get_path", 2018, 1 if Environment::VERSION >= [3, 6]
65
66 def get_path_nocache(filename, fallback_dirs)
67 ext = File.extname(filename.to_s)
68 if ext.empty?
69 get_path_without_extension(filename.to_s, fallback_dirs)
70 else
71 get_path_with_extension(filename.to_s, fallback_dirs)
72 end
73 end
74
75 def get_path_with_extension(filename, fallback_dirs)
76 filename, fallback_dirs = Plugin.filtering(:skin_get, filename, fallback_dirs)
77 [ user_dir, fallback_dirs, default_dir ].flatten.compact.flat_map { |dir|
78 File.join(dir, filename)
79 }.find { |path|
80 FileTest.exist?(path)
81 } || default_image
82 end
83
84 def get_path_without_extension(filename, fallback_dirs)
85 AVAILABLE_EXTENSIONS.lazy.map { |ext|
86 get_path_with_extension("#{filename}.#{ext}", fallback_dirs)
87 }.find{ |ext|
88 ext != default_image
89 } || default_image
90 end
91 end