From 125f856e67b38c075084359f6c58e68415526359 Mon Sep 17 00:00:00 2001 From: John Preston Date: Thu, 24 Aug 2023 18:04:32 +0200 Subject: [PATCH] Proof-of-concept (WebView2 / Local) iv. --- Telegram/CMakeLists.txt | 9 +- .../Resources/iv_html/highlight.9.12.0.css | 1 + .../Resources/iv_html/highlight.9.12.0.js | 3 + Telegram/Resources/iv_html/page.css | 871 ++++++++++++++ Telegram/Resources/iv_html/page.js | 86 ++ Telegram/Resources/qrc/telegram/iv.qrc | 8 + .../boxes/peers/edit_peer_color_box.cpp | 2 + Telegram/SourceFiles/core/application.cpp | 5 + Telegram/SourceFiles/core/application.h | 10 + Telegram/SourceFiles/data/data_session.cpp | 18 + Telegram/SourceFiles/data/data_session.h | 6 + Telegram/SourceFiles/data/data_web_page.cpp | 6 + Telegram/SourceFiles/data/data_web_page.h | 7 + .../history/view/history_view_view_button.cpp | 5 + .../view/media/history_view_web_page.cpp | 31 +- Telegram/SourceFiles/iv/iv_controller.cpp | 115 ++ Telegram/SourceFiles/iv/iv_controller.h | 42 + Telegram/SourceFiles/iv/iv_data.cpp | 63 + Telegram/SourceFiles/iv/iv_data.h | 47 + Telegram/SourceFiles/iv/iv_instance.cpp | 663 +++++++++++ Telegram/SourceFiles/iv/iv_instance.h | 45 + Telegram/SourceFiles/iv/iv_pch.h | 27 + Telegram/SourceFiles/iv/iv_prepare.cpp | 1038 +++++++++++++++++ Telegram/SourceFiles/iv/iv_prepare.h | 25 + Telegram/cmake/td_iv.cmake | 35 + 25 files changed, 3164 insertions(+), 4 deletions(-) create mode 100644 Telegram/Resources/iv_html/highlight.9.12.0.css create mode 100644 Telegram/Resources/iv_html/highlight.9.12.0.js create mode 100644 Telegram/Resources/iv_html/page.css create mode 100644 Telegram/Resources/iv_html/page.js create mode 100644 Telegram/Resources/qrc/telegram/iv.qrc create mode 100644 Telegram/SourceFiles/iv/iv_controller.cpp create mode 100644 Telegram/SourceFiles/iv/iv_controller.h create mode 100644 Telegram/SourceFiles/iv/iv_data.cpp create mode 100644 Telegram/SourceFiles/iv/iv_data.h create mode 100644 Telegram/SourceFiles/iv/iv_instance.cpp create mode 100644 Telegram/SourceFiles/iv/iv_instance.h create mode 100644 Telegram/SourceFiles/iv/iv_pch.h create mode 100644 Telegram/SourceFiles/iv/iv_prepare.cpp create mode 100644 Telegram/SourceFiles/iv/iv_prepare.h create mode 100644 Telegram/cmake/td_iv.cmake diff --git a/Telegram/CMakeLists.txt b/Telegram/CMakeLists.txt index 32acbe57ec..5d30acc969 100644 --- a/Telegram/CMakeLists.txt +++ b/Telegram/CMakeLists.txt @@ -30,8 +30,9 @@ include(cmake/lib_tgvoip.cmake) include(cmake/lib_tgcalls.cmake) include(cmake/lib_prisma.cmake) include(cmake/td_export.cmake) -include(cmake/td_mtproto.cmake) +include(cmake/td_iv.cmake) include(cmake/td_lang.cmake) +include(cmake/td_mtproto.cmake) include(cmake/td_scheme.cmake) include(cmake/td_ui.cmake) include(cmake/generate_appdata_changelog.cmake) @@ -62,8 +63,9 @@ PRIVATE desktop-app::external_minizip tdesktop::td_export - tdesktop::td_mtproto + tdesktop::td_iv tdesktop::td_lang + tdesktop::td_mtproto tdesktop::td_scheme tdesktop::td_ui desktop-app::lib_webrtc @@ -995,6 +997,8 @@ PRIVATE intro/intro_step.h intro/intro_widget.cpp intro/intro_widget.h + iv/iv_instance.cpp + iv/iv_instance.h lang/lang_cloud_manager.cpp lang/lang_cloud_manager.h lang/lang_instance.cpp @@ -1567,6 +1571,7 @@ PRIVATE qrc/emoji_preview.qrc qrc/telegram/animations.qrc qrc/telegram/export.qrc + qrc/telegram/iv.qrc qrc/telegram/telegram.qrc qrc/telegram/sounds.qrc winrc/Telegram.rc diff --git a/Telegram/Resources/iv_html/highlight.9.12.0.css b/Telegram/Resources/iv_html/highlight.9.12.0.css new file mode 100644 index 0000000000..7d8be18d05 --- /dev/null +++ b/Telegram/Resources/iv_html/highlight.9.12.0.css @@ -0,0 +1 @@ +.hljs{display:block;overflow-x:auto;padding:0.5em;background:#F0F0F0}.hljs,.hljs-subst{color:#444}.hljs-comment{color:#888888}.hljs-keyword,.hljs-attribute,.hljs-selector-tag,.hljs-meta-keyword,.hljs-doctag,.hljs-name{font-weight:bold}.hljs-type,.hljs-string,.hljs-number,.hljs-selector-id,.hljs-selector-class,.hljs-quote,.hljs-template-tag,.hljs-deletion{color:#880000}.hljs-title,.hljs-section{color:#880000;font-weight:bold}.hljs-regexp,.hljs-symbol,.hljs-variable,.hljs-template-variable,.hljs-link,.hljs-selector-attr,.hljs-selector-pseudo{color:#BC6060}.hljs-literal{color:#78A960}.hljs-built_in,.hljs-bullet,.hljs-code,.hljs-addition{color:#397300}.hljs-meta{color:#1f7199}.hljs-meta-string{color:#4d99bf}.hljs-emphasis{font-style:italic}.hljs-strong{font-weight:bold} \ No newline at end of file diff --git a/Telegram/Resources/iv_html/highlight.9.12.0.js b/Telegram/Resources/iv_html/highlight.9.12.0.js new file mode 100644 index 0000000000..f30a334c9d --- /dev/null +++ b/Telegram/Resources/iv_html/highlight.9.12.0.js @@ -0,0 +1,3 @@ +/*! highlight.js v9.12.0 | BSD3 License | git.io/hljslicense */ +!function(e){var t="object"==typeof window&&window||"object"==typeof self&&self;"undefined"!=typeof exports?e(exports):t&&(t.hljs=e({}),"function"==typeof define&&define.amd&&define([],function(){return t.hljs}))}(function(e){function t(e){return e.replace(/&/g,"&").replace(//g,">")}function r(e){return e.nodeName.toLowerCase()}function a(e,t){var r=e&&e.exec(t);return r&&0===r.index}function n(e){return E.test(e)}function i(e){var t,r,a,i,s=e.className+" ";if(s+=e.parentNode?e.parentNode.className:"",r=M.exec(s))return w(r[1])?r[1]:"no-highlight";for(s=s.split(/\s+/),t=0,a=s.length;a>t;t++)if(i=s[t],n(i)||w(i))return i}function s(e){var t,r={},a=Array.prototype.slice.call(arguments,1);for(t in e)r[t]=e[t];return a.forEach(function(e){for(t in e)r[t]=e[t]}),r}function c(e){var t=[];return function a(e,n){for(var i=e.firstChild;i;i=i.nextSibling)3===i.nodeType?n+=i.nodeValue.length:1===i.nodeType&&(t.push({event:"start",offset:n,node:i}),n=a(i,n),r(i).match(/br|hr|img|input/)||t.push({event:"stop",offset:n,node:i}));return n}(e,0),t}function o(e,a,n){function i(){return e.length&&a.length?e[0].offset!==a[0].offset?e[0].offset"}function c(e){u+=""}function o(e){("start"===e.event?s:c)(e.node)}for(var l=0,u="",d=[];e.length||a.length;){var b=i();if(u+=t(n.substring(l,b[0].offset)),l=b[0].offset,b===e){d.reverse().forEach(c);do o(b.splice(0,1)[0]),b=i();while(b===e&&b.length&&b[0].offset===l);d.reverse().forEach(s)}else"start"===b[0].event?d.push(b[0].node):d.pop(),o(b.splice(0,1)[0])}return u+t(n.substr(l))}function l(e){return e.v&&!e.cached_variants&&(e.cached_variants=e.v.map(function(t){return s(e,{v:null},t)})),e.cached_variants||e.eW&&[s(e)]||[e]}function u(e){function t(e){return e&&e.source||e}function r(r,a){return new RegExp(t(r),"m"+(e.cI?"i":"")+(a?"g":""))}function a(n,i){if(!n.compiled){if(n.compiled=!0,n.k=n.k||n.bK,n.k){var s={},c=function(t,r){e.cI&&(r=r.toLowerCase()),r.split(" ").forEach(function(e){var r=e.split("|");s[r[0]]=[t,r[1]?Number(r[1]):1]})};"string"==typeof n.k?c("keyword",n.k):k(n.k).forEach(function(e){c(e,n.k[e])}),n.k=s}n.lR=r(n.l||/\w+/,!0),i&&(n.bK&&(n.b="\\b("+n.bK.split(" ").join("|")+")\\b"),n.b||(n.b=/\B|\b/),n.bR=r(n.b),n.e||n.eW||(n.e=/\B|\b/),n.e&&(n.eR=r(n.e)),n.tE=t(n.e)||"",n.eW&&i.tE&&(n.tE+=(n.e?"|":"")+i.tE)),n.i&&(n.iR=r(n.i)),null==n.r&&(n.r=1),n.c||(n.c=[]),n.c=Array.prototype.concat.apply([],n.c.map(function(e){return l("self"===e?n:e)})),n.c.forEach(function(e){a(e,n)}),n.starts&&a(n.starts,i);var o=n.c.map(function(e){return e.bK?"\\.?("+e.b+")\\.?":e.b}).concat([n.tE,n.i]).map(t).filter(Boolean);n.t=o.length?r(o.join("|"),!0):{exec:function(){return null}}}}a(e)}function d(e,r,n,i){function s(e,t){var r,n;for(r=0,n=t.c.length;n>r;r++)if(a(t.c[r].bR,e))return t.c[r]}function c(e,t){if(a(e.eR,t)){for(;e.endsParent&&e.parent;)e=e.parent;return e}return e.eW?c(e.parent,t):void 0}function o(e,t){return!n&&a(t.iR,e)}function l(e,t){var r=v.cI?t[0].toLowerCase():t[0];return e.k.hasOwnProperty(r)&&e.k[r]}function p(e,t,r,a){var n=a?"":L.classPrefix,i='',i+t+s}function m(){var e,r,a,n;if(!N.k)return t(E);for(n="",r=0,N.lR.lastIndex=0,a=N.lR.exec(E);a;)n+=t(E.substring(r,a.index)),e=l(N,a),e?(M+=e[1],n+=p(e[0],t(a[0]))):n+=t(a[0]),r=N.lR.lastIndex,a=N.lR.exec(E);return n+t(E.substr(r))}function f(){var e="string"==typeof N.sL;if(e&&!x[N.sL])return t(E);var r=e?d(N.sL,E,!0,k[N.sL]):b(E,N.sL.length?N.sL:void 0);return N.r>0&&(M+=r.r),e&&(k[N.sL]=r.top),p(r.language,r.value,!1,!0)}function g(){C+=null!=N.sL?f():m(),E=""}function _(e){C+=e.cN?p(e.cN,"",!0):"",N=Object.create(e,{parent:{value:N}})}function h(e,t){if(E+=e,null==t)return g(),0;var r=s(t,N);if(r)return r.skip?E+=t:(r.eB&&(E+=t),g(),r.rB||r.eB||(E=t)),_(r,t),r.rB?0:t.length;var a=c(N,t);if(a){var n=N;n.skip?E+=t:(n.rE||n.eE||(E+=t),g(),n.eE&&(E=t));do N.cN&&(C+=R),N.skip||(M+=N.r),N=N.parent;while(N!==a.parent);return a.starts&&_(a.starts,""),n.rE?0:t.length}if(o(t,N))throw new Error('Illegal lexeme "'+t+'" for mode "'+(N.cN||"")+'"');return E+=t,t.length||1}var v=w(e);if(!v)throw new Error('Unknown language: "'+e+'"');u(v);var y,N=i||v,k={},C="";for(y=N;y!==v;y=y.parent)y.cN&&(C=p(y.cN,"",!0)+C);var E="",M=0;try{for(var B,S,$=0;;){if(N.t.lastIndex=$,B=N.t.exec(r),!B)break;S=h(r.substring($,B.index),B[0]),$=B.index+S}for(h(r.substr($)),y=N;y.parent;y=y.parent)y.cN&&(C+=R);return{r:M,value:C,language:e,top:N}}catch(A){if(A.message&&-1!==A.message.indexOf("Illegal"))return{r:0,value:t(r)};throw A}}function b(e,r){r=r||L.languages||k(x);var a={r:0,value:t(e)},n=a;return r.filter(w).forEach(function(t){var r=d(t,e,!1);r.language=t,r.r>n.r&&(n=r),r.r>a.r&&(n=a,a=r)}),n.language&&(a.second_best=n),a}function p(e){return L.tabReplace||L.useBR?e.replace(B,function(e,t){return L.useBR&&"\n"===e?"
":L.tabReplace?t.replace(/\t/g,L.tabReplace):""}):e}function m(e,t,r){var a=t?C[t]:r,n=[e.trim()];return e.match(/\bhljs\b/)||n.push("hljs"),-1===e.indexOf(a)&&n.push(a),n.join(" ").trim()}function f(e){var t,r,a,s,l,u=i(e);n(u)||(L.useBR?(t=document.createElementNS("http://www.w3.org/1999/xhtml","div"),t.innerHTML=e.innerHTML.replace(/\n/g,"").replace(//g,"\n")):t=e,l=t.textContent,a=u?d(u,l,!0):b(l),r=c(t),r.length&&(s=document.createElementNS("http://www.w3.org/1999/xhtml","div"),s.innerHTML=a.value,a.value=o(r,c(s),l)),a.value=p(a.value),e.innerHTML=a.value,e.className=m(e.className,u,a.language),e.result={language:a.language,re:a.r},a.second_best&&(e.second_best={language:a.second_best.language,re:a.second_best.r}))}function g(e){L=s(L,e)}function _(){if(!_.called){_.called=!0;var e=document.querySelectorAll("pre code");N.forEach.call(e,f)}}function h(){addEventListener("DOMContentLoaded",_,!1),addEventListener("load",_,!1)}function v(t,r){var a=x[t]=r(e);a.aliases&&a.aliases.forEach(function(e){C[e]=t})}function y(){return k(x)}function w(e){return e=(e||"").toLowerCase(),x[e]||x[C[e]]}var N=[],k=Object.keys,x={},C={},E=/^(no-?highlight|plain|text)$/i,M=/\blang(?:uage)?-([\w-]+)\b/i,B=/((^(<[^>]+>|\t|)+|(?:\n)))/gm,R="
",L={classPrefix:"hljs-",tabReplace:null,useBR:!1,languages:void 0};return e.highlight=d,e.highlightAuto=b,e.fixMarkup=p,e.highlightBlock=f,e.configure=g,e.initHighlighting=_,e.initHighlightingOnLoad=h,e.registerLanguage=v,e.listLanguages=y,e.getLanguage=w,e.inherit=s,e.IR="[a-zA-Z]\\w*",e.UIR="[a-zA-Z_]\\w*",e.NR="\\b\\d+(\\.\\d+)?",e.CNR="(-?)(\\b0[xX][a-fA-F0-9]+|(\\b\\d+(\\.\\d*)?|\\.\\d+)([eE][-+]?\\d+)?)",e.BNR="\\b(0b[01]+)",e.RSR="!|!=|!==|%|%=|&|&&|&=|\\*|\\*=|\\+|\\+=|,|-|-=|/=|/|:|;|<<|<<=|<=|<|===|==|=|>>>=|>>=|>=|>>>|>>|>|\\?|\\[|\\{|\\(|\\^|\\^=|\\||\\|=|\\|\\||~",e.BE={b:"\\\\[\\s\\S]",r:0},e.ASM={cN:"string",b:"'",e:"'",i:"\\n",c:[e.BE]},e.QSM={cN:"string",b:'"',e:'"',i:"\\n",c:[e.BE]},e.PWM={b:/\b(a|an|the|are|I'm|isn't|don't|doesn't|won't|but|just|should|pretty|simply|enough|gonna|going|wtf|so|such|will|you|your|they|like|more)\b/},e.C=function(t,r,a){var n=e.inherit({cN:"comment",b:t,e:r,c:[]},a||{});return n.c.push(e.PWM),n.c.push({cN:"doctag",b:"(?:TODO|FIXME|NOTE|BUG|XXX):",r:0}),n},e.CLCM=e.C("//","$"),e.CBCM=e.C("/\\*","\\*/"),e.HCM=e.C("#","$"),e.NM={cN:"number",b:e.NR,r:0},e.CNM={cN:"number",b:e.CNR,r:0},e.BNM={cN:"number",b:e.BNR,r:0},e.CSSNM={cN:"number",b:e.NR+"(%|em|ex|ch|rem|vw|vh|vmin|vmax|cm|mm|in|pt|pc|px|deg|grad|rad|turn|s|ms|Hz|kHz|dpi|dpcm|dppx)?",r:0},e.RM={cN:"regexp",b:/\//,e:/\/[gimuy]*/,i:/\n/,c:[e.BE,{b:/\[/,e:/\]/,r:0,c:[e.BE]}]},e.TM={cN:"title",b:e.IR,r:0},e.UTM={cN:"title",b:e.UIR,r:0},e.METHOD_GUARD={b:"\\.\\s*"+e.UIR,r:0},e.registerLanguage("apache",function(e){var t={cN:"number",b:"[\\$%]\\d+"};return{aliases:["apacheconf"],cI:!0,c:[e.HCM,{cN:"section",b:""},{cN:"attribute",b:/\w+/,r:0,k:{nomarkup:"order deny allow setenv rewriterule rewriteengine rewritecond documentroot sethandler errordocument loadmodule options header listen serverroot servername"},starts:{e:/$/,r:0,k:{literal:"on off all"},c:[{cN:"meta",b:"\\s\\[",e:"\\]$"},{cN:"variable",b:"[\\$%]\\{",e:"\\}",c:["self",t]},t,e.QSM]}}],i:/\S/}}),e.registerLanguage("bash",function(e){var t={cN:"variable",v:[{b:/\$[\w\d#@][\w\d_]*/},{b:/\$\{(.*?)}/}]},r={cN:"string",b:/"/,e:/"/,c:[e.BE,t,{cN:"variable",b:/\$\(/,e:/\)/,c:[e.BE]}]},a={cN:"string",b:/'/,e:/'/};return{aliases:["sh","zsh"],l:/\b-?[a-z\._]+\b/,k:{keyword:"if then else elif fi for while in do done case esac function",literal:"true false",built_in:"break cd continue eval exec exit export getopts hash pwd readonly return shift test times trap umask unset alias bind builtin caller command declare echo enable help let local logout mapfile printf read readarray source type typeset ulimit unalias set shopt autoload bg bindkey bye cap chdir clone comparguments compcall compctl compdescribe compfiles compgroups compquote comptags comptry compvalues dirs disable disown echotc echoti emulate fc fg float functions getcap getln history integer jobs kill limit log noglob popd print pushd pushln rehash sched setcap setopt stat suspend ttyctl unfunction unhash unlimit unsetopt vared wait whence where which zcompile zformat zftp zle zmodload zparseopts zprof zpty zregexparse zsocket zstyle ztcp",_:"-ne -eq -lt -gt -f -d -e -s -l -a"},c:[{cN:"meta",b:/^#![^\n]+sh\s*$/,r:10},{cN:"function",b:/\w[\w\d_]*\s*\(\s*\)\s*\{/,rB:!0,c:[e.inherit(e.TM,{b:/\w[\w\d_]*/})],r:0},e.HCM,r,a,t]}}),e.registerLanguage("coffeescript",function(e){var t={keyword:"in if for while finally new do return else break catch instanceof throw try this switch continue typeof delete debugger super yield import export from as default await then unless until loop of by when and or is isnt not",literal:"true false null undefined yes no on off",built_in:"npm require console print module global window document"},r="[A-Za-z$_][0-9A-Za-z$_]*",a={cN:"subst",b:/#\{/,e:/}/,k:t},n=[e.BNM,e.inherit(e.CNM,{starts:{e:"(\\s*/)?",r:0}}),{cN:"string",v:[{b:/'''/,e:/'''/,c:[e.BE]},{b:/'/,e:/'/,c:[e.BE]},{b:/"""/,e:/"""/,c:[e.BE,a]},{b:/"/,e:/"/,c:[e.BE,a]}]},{cN:"regexp",v:[{b:"///",e:"///",c:[a,e.HCM]},{b:"//[gim]*",r:0},{b:/\/(?![ *])(\\\/|.)*?\/[gim]*(?=\W|$)/}]},{b:"@"+r},{sL:"javascript",eB:!0,eE:!0,v:[{b:"```",e:"```"},{b:"`",e:"`"}]}];a.c=n;var i=e.inherit(e.TM,{b:r}),s="(\\(.*\\))?\\s*\\B[-=]>",c={cN:"params",b:"\\([^\\(]",rB:!0,c:[{b:/\(/,e:/\)/,k:t,c:["self"].concat(n)}]};return{aliases:["coffee","cson","iced"],k:t,i:/\/\*/,c:n.concat([e.C("###","###"),e.HCM,{cN:"function",b:"^\\s*"+r+"\\s*=\\s*"+s,e:"[-=]>",rB:!0,c:[i,c]},{b:/[:\(,=]\s*/,r:0,c:[{cN:"function",b:s,e:"[-=]>",rB:!0,c:[c]}]},{cN:"class",bK:"class",e:"$",i:/[:="\[\]]/,c:[{bK:"extends",eW:!0,i:/[:="\[\]]/,c:[i]},i]},{b:r+":",e:":",rB:!0,rE:!0,r:0}])}}),e.registerLanguage("cpp",function(e){var t={cN:"keyword",b:"\\b[a-z\\d_]*_t\\b"},r={cN:"string",v:[{b:'(u8?|U)?L?"',e:'"',i:"\\n",c:[e.BE]},{b:'(u8?|U)?R"',e:'"',c:[e.BE]},{b:"'\\\\?.",e:"'",i:"."}]},a={cN:"number",v:[{b:"\\b(0b[01']+)"},{b:"(-?)\\b([\\d']+(\\.[\\d']*)?|\\.[\\d']+)(u|U|l|L|ul|UL|f|F|b|B)"},{b:"(-?)(\\b0[xX][a-fA-F0-9']+|(\\b[\\d']+(\\.[\\d']*)?|\\.[\\d']+)([eE][-+]?[\\d']+)?)"}],r:0},n={cN:"meta",b:/#\s*[a-z]+\b/,e:/$/,k:{"meta-keyword":"if else elif endif define undef warning error line pragma ifdef ifndef include"},c:[{b:/\\\n/,r:0},e.inherit(r,{cN:"meta-string"}),{cN:"meta-string",b:/<[^\n>]*>/,e:/$/,i:"\\n"},e.CLCM,e.CBCM]},i=e.IR+"\\s*\\(",s={keyword:"int float while private char catch import module export virtual operator sizeof dynamic_cast|10 typedef const_cast|10 const for static_cast|10 union namespace unsigned long volatile static protected bool template mutable if public friend do goto auto void enum else break extern using asm case typeid short reinterpret_cast|10 default double register explicit signed typename try this switch continue inline delete alignof constexpr decltype noexcept static_assert thread_local restrict _Bool complex _Complex _Imaginary atomic_bool atomic_char atomic_schar atomic_uchar atomic_short atomic_ushort atomic_int atomic_uint atomic_long atomic_ulong atomic_llong atomic_ullong new throw return and or not",built_in:"std string cin cout cerr clog stdin stdout stderr stringstream istringstream ostringstream auto_ptr deque list queue stack vector map set bitset multiset multimap unordered_set unordered_map unordered_multiset unordered_multimap array shared_ptr abort abs acos asin atan2 atan calloc ceil cosh cos exit exp fabs floor fmod fprintf fputs free frexp fscanf isalnum isalpha iscntrl isdigit isgraph islower isprint ispunct isspace isupper isxdigit tolower toupper labs ldexp log10 log malloc realloc memchr memcmp memcpy memset modf pow printf putchar puts scanf sinh sin snprintf sprintf sqrt sscanf strcat strchr strcmp strcpy strcspn strlen strncat strncmp strncpy strpbrk strrchr strspn strstr tanh tan vfprintf vprintf vsprintf endl initializer_list unique_ptr",literal:"true false nullptr NULL"},c=[t,e.CLCM,e.CBCM,a,r];return{aliases:["c","cc","h","c++","h++","hpp"],k:s,i:"",k:s,c:["self",t]},{b:e.IR+"::",k:s},{v:[{b:/=/,e:/;/},{b:/\(/,e:/\)/},{bK:"new throw return else",e:/;/}],k:s,c:c.concat([{b:/\(/,e:/\)/,k:s,c:c.concat(["self"]),r:0}]),r:0},{cN:"function",b:"("+e.IR+"[\\*&\\s]+)+"+i,rB:!0,e:/[{;=]/,eE:!0,k:s,i:/[^\w\s\*&]/,c:[{b:i,rB:!0,c:[e.TM],r:0},{cN:"params",b:/\(/,e:/\)/,k:s,r:0,c:[e.CLCM,e.CBCM,r,a,t]},e.CLCM,e.CBCM,n]},{cN:"class",bK:"class struct",e:/[{;:]/,c:[{b://,c:["self"]},e.TM]}]),exports:{preprocessor:n,strings:r,k:s}}}),e.registerLanguage("cs",function(e){var t={keyword:"abstract as base bool break byte case catch char checked const continue decimal default delegate do double enum event explicit extern finally fixed float for foreach goto if implicit in int interface internal is lock long nameof object operator out override params private protected public readonly ref sbyte sealed short sizeof stackalloc static string struct switch this try typeof uint ulong unchecked unsafe ushort using virtual void volatile while add alias ascending async await by descending dynamic equals from get global group into join let on orderby partial remove select set value var where yield",literal:"null false true"},r={cN:"string",b:'@"',e:'"',c:[{b:'""'}]},a=e.inherit(r,{i:/\n/}),n={cN:"subst",b:"{",e:"}",k:t},i=e.inherit(n,{i:/\n/}),s={cN:"string",b:/\$"/,e:'"',i:/\n/,c:[{b:"{{"},{b:"}}"},e.BE,i]},c={cN:"string",b:/\$@"/,e:'"',c:[{b:"{{"},{b:"}}"},{b:'""'},n]},o=e.inherit(c,{i:/\n/,c:[{b:"{{"},{b:"}}"},{b:'""'},i]});n.c=[c,s,r,e.ASM,e.QSM,e.CNM,e.CBCM],i.c=[o,s,a,e.ASM,e.QSM,e.CNM,e.inherit(e.CBCM,{i:/\n/})];var l={v:[c,s,r,e.ASM,e.QSM]},u=e.IR+"(<"+e.IR+"(\\s*,\\s*"+e.IR+")*>)?(\\[\\])?";return{aliases:["csharp"],k:t,i:/::/,c:[e.C("///","$",{rB:!0,c:[{cN:"doctag",v:[{b:"///",r:0},{b:""},{b:""}]}]}),e.CLCM,e.CBCM,{cN:"meta",b:"#",e:"$",k:{"meta-keyword":"if else elif endif define undef warning error line region endregion pragma checksum"}},l,e.CNM,{bK:"class interface",e:/[{;=]/,i:/[^\s:]/,c:[e.TM,e.CLCM,e.CBCM]},{bK:"namespace",e:/[{;=]/,i:/[^\s:]/,c:[e.inherit(e.TM,{b:"[a-zA-Z](\\.?\\w)*"}),e.CLCM,e.CBCM]},{cN:"meta",b:"^\\s*\\[",eB:!0,e:"\\]",eE:!0,c:[{cN:"meta-string",b:/"/,e:/"/}]},{bK:"new return throw await else",r:0},{cN:"function",b:"("+u+"\\s+)+"+e.IR+"\\s*\\(",rB:!0,e:/[{;=]/,eE:!0,k:t,c:[{b:e.IR+"\\s*\\(",rB:!0,c:[e.TM],r:0},{cN:"params",b:/\(/,e:/\)/,eB:!0,eE:!0,k:t,r:0,c:[l,e.CNM,e.CBCM]},e.CLCM,e.CBCM]}]}}),e.registerLanguage("css",function(e){var t="[a-zA-Z-][a-zA-Z0-9_-]*",r={b:/[A-Z\_\.\-]+\s*:/,rB:!0,e:";",eW:!0,c:[{cN:"attribute",b:/\S/,e:":",eE:!0,starts:{eW:!0,eE:!0,c:[{b:/[\w-]+\(/,rB:!0,c:[{cN:"built_in",b:/[\w-]+/},{b:/\(/,e:/\)/,c:[e.ASM,e.QSM]}]},e.CSSNM,e.QSM,e.ASM,e.CBCM,{cN:"number",b:"#[0-9A-Fa-f]+"},{cN:"meta",b:"!important"}]}}]};return{cI:!0,i:/[=\/|'\$]/,c:[e.CBCM,{cN:"selector-id",b:/#[A-Za-z0-9_-]+/},{cN:"selector-class",b:/\.[A-Za-z0-9_-]+/},{cN:"selector-attr",b:/\[/,e:/\]/,i:"$"},{cN:"selector-pseudo",b:/:(:)?[a-zA-Z0-9\_\-\+\(\)"'.]+/},{b:"@(font-face|page)",l:"[a-z-]+",k:"font-face page"},{b:"@",e:"[{;]",i:/:/,c:[{cN:"keyword",b:/\w+/},{b:/\s/,eW:!0,eE:!0,r:0,c:[e.ASM,e.QSM,e.CSSNM]}]},{cN:"selector-tag",b:t,r:0},{b:"{",e:"}",i:/\S/,c:[e.CBCM,r]}]}}),e.registerLanguage("diff",function(e){return{aliases:["patch"],c:[{cN:"meta",r:10,v:[{b:/^@@ +\-\d+,\d+ +\+\d+,\d+ +@@$/},{b:/^\*\*\* +\d+,\d+ +\*\*\*\*$/},{b:/^\-\-\- +\d+,\d+ +\-\-\-\-$/}]},{cN:"comment",v:[{b:/Index: /,e:/$/},{b:/={3,}/,e:/$/},{b:/^\-{3}/,e:/$/},{b:/^\*{3} /,e:/$/},{b:/^\+{3}/,e:/$/},{b:/\*{5}/,e:/\*{5}$/}]},{cN:"addition",b:"^\\+",e:"$"},{cN:"deletion",b:"^\\-",e:"$"},{cN:"addition",b:"^\\!",e:"$"}]}}),e.registerLanguage("http",function(e){var t="HTTP/[0-9\\.]+";return{aliases:["https"],i:"\\S",c:[{b:"^"+t,e:"$",c:[{cN:"number",b:"\\b\\d{3}\\b"}]},{b:"^[A-Z]+ (.*?) "+t+"$",rB:!0,e:"$",c:[{cN:"string",b:" ",e:" ",eB:!0,eE:!0},{b:t},{cN:"keyword",b:"[A-Z]+"}]},{cN:"attribute",b:"^\\w",e:": ",eE:!0,i:"\\n|\\s|=",starts:{e:"$",r:0}},{b:"\\n\\n",starts:{sL:[],eW:!0}}]}}),e.registerLanguage("ini",function(e){var t={cN:"string",c:[e.BE],v:[{b:"'''",e:"'''",r:10},{b:'"""',e:'"""',r:10},{b:'"',e:'"'},{b:"'",e:"'"}]};return{aliases:["toml"],cI:!0,i:/\S/,c:[e.C(";","$"),e.HCM,{cN:"section",b:/^\s*\[+/,e:/\]+/},{b:/^[a-z0-9\[\]_-]+\s*=\s*/,e:"$",rB:!0,c:[{cN:"attr",b:/[a-z0-9\[\]_-]+/},{b:/=/,eW:!0,r:0,c:[{cN:"literal",b:/\bon|off|true|false|yes|no\b/},{cN:"variable",v:[{b:/\$[\w\d"][\w\d_]*/},{b:/\$\{(.*?)}/}]},t,{cN:"number",b:/([\+\-]+)?[\d]+_[\d_]+/},e.NM]}]}]}}),e.registerLanguage("java",function(e){var t="[À-ʸa-zA-Z_$][À-ʸa-zA-Z_$0-9]*",r=t+"(<"+t+"(\\s*,\\s*"+t+")*>)?",a="false synchronized int abstract float private char boolean static null if const for true while long strictfp finally protected import native final void enum else break transient catch instanceof byte super volatile case assert short package default double public try this switch continue throws protected public private module requires exports do",n="\\b(0[bB]([01]+[01_]+[01]+|[01]+)|0[xX]([a-fA-F0-9]+[a-fA-F0-9_]+[a-fA-F0-9]+|[a-fA-F0-9]+)|(([\\d]+[\\d_]+[\\d]+|[\\d]+)(\\.([\\d]+[\\d_]+[\\d]+|[\\d]+))?|\\.([\\d]+[\\d_]+[\\d]+|[\\d]+))([eE][-+]?\\d+)?)[lLfF]?",i={cN:"number",b:n,r:0};return{aliases:["jsp"],k:a,i:/<\/|#/,c:[e.C("/\\*\\*","\\*/",{r:0,c:[{b:/\w+@/,r:0},{cN:"doctag",b:"@[A-Za-z]+"}]}),e.CLCM,e.CBCM,e.ASM,e.QSM,{cN:"class",bK:"class interface",e:/[{;=]/,eE:!0,k:"class interface",i:/[:"\[\]]/,c:[{bK:"extends implements"},e.UTM]},{bK:"new throw return else",r:0},{cN:"function",b:"("+r+"\\s+)+"+e.UIR+"\\s*\\(",rB:!0,e:/[{;=]/,eE:!0,k:a,c:[{b:e.UIR+"\\s*\\(",rB:!0,r:0,c:[e.UTM]},{cN:"params",b:/\(/,e:/\)/,k:a,r:0,c:[e.ASM,e.QSM,e.CNM,e.CBCM]},e.CLCM,e.CBCM]},i,{cN:"meta",b:"@[A-Za-z]+"}]}}),e.registerLanguage("javascript",function(e){var t="[A-Za-z$_][0-9A-Za-z$_]*",r={keyword:"in of if for while finally var new function do return void else break catch instanceof with throw case default try this switch continue typeof delete let yield const export super debugger as async await static import from as",literal:"true false null undefined NaN Infinity",built_in:"eval isFinite isNaN parseFloat parseInt decodeURI decodeURIComponent encodeURI encodeURIComponent escape unescape Object Function Boolean Error EvalError InternalError RangeError ReferenceError StopIteration SyntaxError TypeError URIError Number Math Date String RegExp Array Float32Array Float64Array Int16Array Int32Array Int8Array Uint16Array Uint32Array Uint8Array Uint8ClampedArray ArrayBuffer DataView JSON Intl arguments require module console window document Symbol Set Map WeakSet WeakMap Proxy Reflect Promise"},a={cN:"number",v:[{b:"\\b(0[bB][01]+)"},{b:"\\b(0[oO][0-7]+)"},{b:e.CNR}],r:0},n={cN:"subst",b:"\\$\\{",e:"\\}",k:r,c:[]},i={cN:"string",b:"`",e:"`",c:[e.BE,n]};n.c=[e.ASM,e.QSM,i,a,e.RM];var s=n.c.concat([e.CBCM,e.CLCM]);return{aliases:["js","jsx"],k:r,c:[{cN:"meta",r:10,b:/^\s*['"]use (strict|asm)['"]/},{cN:"meta",b:/^#!/,e:/$/},e.ASM,e.QSM,i,e.CLCM,e.CBCM,a,{b:/[{,]\s*/,r:0,c:[{b:t+"\\s*:",rB:!0,r:0,c:[{cN:"attr",b:t,r:0}]}]},{b:"("+e.RSR+"|\\b(case|return|throw)\\b)\\s*",k:"return throw case",c:[e.CLCM,e.CBCM,e.RM,{cN:"function",b:"(\\(.*?\\)|"+t+")\\s*=>",rB:!0,e:"\\s*=>",c:[{cN:"params",v:[{b:t},{b:/\(\s*\)/},{b:/\(/,e:/\)/,eB:!0,eE:!0,k:r,c:s}]}]},{b://,sL:"xml",c:[{b:/<\w+\s*\/>/,skip:!0},{b:/<\w+/,e:/(\/\w+|\w+\/)>/,skip:!0,c:[{b:/<\w+\s*\/>/,skip:!0},"self"]}]}],r:0},{cN:"function",bK:"function",e:/\{/,eE:!0,c:[e.inherit(e.TM,{b:t}),{cN:"params",b:/\(/,e:/\)/,eB:!0,eE:!0,c:s}],i:/\[|%/},{b:/\$[(.]/},e.METHOD_GUARD,{cN:"class",bK:"class",e:/[{;=]/,eE:!0,i:/[:"\[\]]/,c:[{bK:"extends"},e.UTM]},{bK:"constructor",e:/\{/,eE:!0}],i:/#(?!!)/}}),e.registerLanguage("json",function(e){var t={literal:"true false null"},r=[e.QSM,e.CNM],a={e:",",eW:!0,eE:!0,c:r,k:t},n={b:"{",e:"}",c:[{cN:"attr",b:/"/,e:/"/,c:[e.BE],i:"\\n"},e.inherit(a,{b:/:/})],i:"\\S"},i={b:"\\[",e:"\\]",c:[e.inherit(a)],i:"\\S"};return r.splice(r.length,0,n,i),{c:r,k:t,i:"\\S"}}),e.registerLanguage("makefile",function(e){var t={cN:"variable",v:[{b:"\\$\\("+e.UIR+"\\)",c:[e.BE]},{b:/\$[@%`]+/}]}]}]};return{aliases:["html","xhtml","rss","atom","xjb","xsd","xsl","plist"],cI:!0,c:[{cN:"meta",b:"",r:10,c:[{b:"\\[",e:"\\]"}]},e.C("",{r:10}),{b:"<\\!\\[CDATA\\[",e:"\\]\\]>",r:10},{b:/<\?(php)?/,e:/\?>/,sL:"php",c:[{b:"/\\*",e:"\\*/",skip:!0}]},{cN:"tag",b:"|$)",e:">",k:{name:"style"},c:[r],starts:{e:"",rE:!0,sL:["css","xml"]}},{cN:"tag",b:"|$)",e:">",k:{name:"script"},c:[r],starts:{e:"",rE:!0,sL:["actionscript","javascript","handlebars","xml"]}},{cN:"meta",v:[{b:/<\?xml/,e:/\?>/,r:10},{b:/<\?\w+/,e:/\?>/}]},{cN:"tag",b:"",c:[{cN:"name",b:/[^\/><\s]+/,r:0},r]}]}}),e.registerLanguage("markdown",function(e){return{aliases:["md","mkdown","mkd"],c:[{cN:"section",v:[{b:"^#{1,6}",e:"$"},{b:"^.+?\\n[=-]{2,}$"}]},{b:"<",e:">",sL:"xml",r:0},{cN:"bullet",b:"^([*+-]|(\\d+\\.))\\s+"},{cN:"strong",b:"[*_]{2}.+?[*_]{2}"},{cN:"emphasis",v:[{b:"\\*.+?\\*"},{b:"_.+?_",r:0}]},{cN:"quote",b:"^>\\s+",e:"$"},{cN:"code",v:[{b:"^```w*s*$",e:"^```s*$"},{b:"`.+?`"},{b:"^( {4}| )",e:"$",r:0}]},{b:"^[-\\*]{3,}",e:"$"},{b:"\\[.+?\\][\\(\\[].*?[\\)\\]]",rB:!0,c:[{cN:"string",b:"\\[",e:"\\]",eB:!0,rE:!0,r:0},{cN:"link",b:"\\]\\(",e:"\\)",eB:!0,eE:!0},{cN:"symbol",b:"\\]\\[",e:"\\]",eB:!0,eE:!0}],r:10},{b:/^\[[^\n]+\]:/,rB:!0,c:[{cN:"symbol",b:/\[/,e:/\]/,eB:!0,eE:!0},{cN:"link",b:/:\s*/,e:/$/,eB:!0}]}]}}),e.registerLanguage("nginx",function(e){var t={cN:"variable",v:[{b:/\$\d+/},{b:/\$\{/,e:/}/},{b:"[\\$\\@]"+e.UIR}]},r={eW:!0,l:"[a-z/_]+",k:{literal:"on off yes no true false none blocked debug info notice warn error crit select break last permanent redirect kqueue rtsig epoll poll /dev/poll"},r:0,i:"=>",c:[e.HCM,{cN:"string",c:[e.BE,t],v:[{b:/"/,e:/"/},{b:/'/,e:/'/}]},{b:"([a-z]+):/",e:"\\s",eW:!0,eE:!0,c:[t]},{cN:"regexp",c:[e.BE,t],v:[{b:"\\s\\^",e:"\\s|{|;",rE:!0},{b:"~\\*?\\s+",e:"\\s|{|;",rE:!0},{b:"\\*(\\.[a-z\\-]+)+"},{b:"([a-z\\-]+\\.)+\\*"}]},{cN:"number",b:"\\b\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}(:\\d{1,5})?\\b"},{cN:"number",b:"\\b\\d+[kKmMgGdshdwy]*\\b",r:0},t]};return{aliases:["nginxconf"],c:[e.HCM,{b:e.UIR+"\\s+{",rB:!0,e:"{",c:[{cN:"section",b:e.UIR}],r:0},{b:e.UIR+"\\s",e:";|{",rB:!0,c:[{cN:"attribute",b:e.UIR,starts:r}],r:0}],i:"[^\\s\\}]"}}),e.registerLanguage("objectivec",function(e){var t={cN:"built_in",b:"\\b(AV|CA|CF|CG|CI|CL|CM|CN|CT|MK|MP|MTK|MTL|NS|SCN|SK|UI|WK|XC)\\w+"},r={keyword:"int float while char export sizeof typedef const struct for union unsigned long volatile static bool mutable if do return goto void enum else break extern asm case short default double register explicit signed typename this switch continue wchar_t inline readonly assign readwrite self @synchronized id typeof nonatomic super unichar IBOutlet IBAction strong weak copy in out inout bycopy byref oneway __strong __weak __block __autoreleasing @private @protected @public @try @property @end @throw @catch @finally @autoreleasepool @synthesize @dynamic @selector @optional @required @encode @package @import @defs @compatibility_alias __bridge __bridge_transfer __bridge_retained __bridge_retain __covariant __contravariant __kindof _Nonnull _Nullable _Null_unspecified __FUNCTION__ __PRETTY_FUNCTION__ __attribute__ getter setter retain unsafe_unretained nonnull nullable null_unspecified null_resettable class instancetype NS_DESIGNATED_INITIALIZER NS_UNAVAILABLE NS_REQUIRES_SUPER NS_RETURNS_INNER_POINTER NS_INLINE NS_AVAILABLE NS_DEPRECATED NS_ENUM NS_OPTIONS NS_SWIFT_UNAVAILABLE NS_ASSUME_NONNULL_BEGIN NS_ASSUME_NONNULL_END NS_REFINED_FOR_SWIFT NS_SWIFT_NAME NS_SWIFT_NOTHROW NS_DURING NS_HANDLER NS_ENDHANDLER NS_VALUERETURN NS_VOIDRETURN",literal:"false true FALSE TRUE nil YES NO NULL",built_in:"BOOL dispatch_once_t dispatch_queue_t dispatch_sync dispatch_async dispatch_once"},a=/[a-zA-Z@][a-zA-Z0-9_]*/,n="@interface @class @protocol @implementation";return{aliases:["mm","objc","obj-c"],k:r,l:a,i:""}]}]},{cN:"class",b:"("+n.split(" ").join("|")+")\\b",e:"({|$)",eE:!0,k:n,l:a,c:[e.UTM]},{b:"\\."+e.UIR,r:0}]}}),e.registerLanguage("perl",function(e){var t="getpwent getservent quotemeta msgrcv scalar kill dbmclose undef lc ma syswrite tr send umask sysopen shmwrite vec qx utime local oct semctl localtime readpipe do return format read sprintf dbmopen pop getpgrp not getpwnam rewinddir qqfileno qw endprotoent wait sethostent bless s|0 opendir continue each sleep endgrent shutdown dump chomp connect getsockname die socketpair close flock exists index shmgetsub for endpwent redo lstat msgctl setpgrp abs exit select print ref gethostbyaddr unshift fcntl syscall goto getnetbyaddr join gmtime symlink semget splice x|0 getpeername recv log setsockopt cos last reverse gethostbyname getgrnam study formline endhostent times chop length gethostent getnetent pack getprotoent getservbyname rand mkdir pos chmod y|0 substr endnetent printf next open msgsnd readdir use unlink getsockopt getpriority rindex wantarray hex system getservbyport endservent int chr untie rmdir prototype tell listen fork shmread ucfirst setprotoent else sysseek link getgrgid shmctl waitpid unpack getnetbyname reset chdir grep split require caller lcfirst until warn while values shift telldir getpwuid my getprotobynumber delete and sort uc defined srand accept package seekdir getprotobyname semop our rename seek if q|0 chroot sysread setpwent no crypt getc chown sqrt write setnetent setpriority foreach tie sin msgget map stat getlogin unless elsif truncate exec keys glob tied closedirioctl socket readlink eval xor readline binmode setservent eof ord bind alarm pipe atan2 getgrent exp time push setgrent gt lt or ne m|0 break given say state when",r={cN:"subst",b:"[$@]\\{",e:"\\}",k:t},a={b:"->{",e:"}"},n={v:[{b:/\$\d/},{b:/[\$%@](\^\w\b|#\w+(::\w+)*|{\w+}|\w+(::\w*)*)/},{b:/[\$%@][^\s\w{]/,r:0}]},i=[e.BE,r,n],s=[n,e.HCM,e.C("^\\=\\w","\\=cut",{eW:!0}),a,{cN:"string",c:i,v:[{b:"q[qwxr]?\\s*\\(",e:"\\)",r:5},{b:"q[qwxr]?\\s*\\[",e:"\\]",r:5},{b:"q[qwxr]?\\s*\\{",e:"\\}",r:5},{b:"q[qwxr]?\\s*\\|",e:"\\|",r:5},{b:"q[qwxr]?\\s*\\<",e:"\\>",r:5},{b:"qw\\s+q",e:"q",r:5},{b:"'",e:"'",c:[e.BE]},{b:'"',e:'"'},{b:"`",e:"`",c:[e.BE]},{b:"{\\w+}",c:[],r:0},{b:"-?\\w+\\s*\\=\\>",c:[],r:0}]},{cN:"number",b:"(\\b0[0-7_]+)|(\\b0x[0-9a-fA-F_]+)|(\\b[1-9][0-9_]*(\\.[0-9_]+)?)|[0_]\\b",r:0},{b:"(\\/\\/|"+e.RSR+"|\\b(split|return|print|reverse|grep)\\b)\\s*",k:"split return print reverse grep",r:0,c:[e.HCM,{cN:"regexp",b:"(s|tr|y)/(\\\\.|[^/])*/(\\\\.|[^/])*/[a-z]*",r:10},{cN:"regexp",b:"(m|qr)?/",e:"/[a-z]*",c:[e.BE],r:0}]},{cN:"function",bK:"sub",e:"(\\s*\\(.*?\\))?[;{]",eE:!0,r:5,c:[e.TM]},{b:"-\\w\\b",r:0},{b:"^__DATA__$",e:"^__END__$",sL:"mojolicious",c:[{b:"^@@.*",e:"$",cN:"comment"}]}];return r.c=s,a.c=s,{aliases:["pl","pm"],l:/[\w\.]+/,k:t,c:s}}),e.registerLanguage("php",function(e){var t={b:"\\$+[a-zA-Z_-ÿ][a-zA-Z0-9_-ÿ]*"},r={cN:"meta",b:/<\?(php)?|\?>/},a={cN:"string",c:[e.BE,r],v:[{b:'b"',e:'"'},{b:"b'",e:"'"},e.inherit(e.ASM,{i:null}),e.inherit(e.QSM,{i:null})]},n={v:[e.BNM,e.CNM]};return{aliases:["php3","php4","php5","php6"],cI:!0,k:"and include_once list abstract global private echo interface as static endswitch array null if endwhile or const for endforeach self var while isset public protected exit foreach throw elseif include __FILE__ empty require_once do xor return parent clone use __CLASS__ __LINE__ else break print eval new catch __METHOD__ case exception default die require __FUNCTION__ enddeclare final try switch continue endfor endif declare unset true false trait goto instanceof insteadof __DIR__ __NAMESPACE__ yield finally",c:[e.HCM,e.C("//","$",{c:[r]}),e.C("/\\*","\\*/",{c:[{cN:"doctag",b:"@[A-Za-z]+"}]}),e.C("__halt_compiler.+?;",!1,{eW:!0,k:"__halt_compiler",l:e.UIR}),{cN:"string",b:/<<<['"]?\w+['"]?$/,e:/^\w+;?$/,c:[e.BE,{cN:"subst",v:[{b:/\$\w+/},{b:/\{\$/,e:/\}/}]}]},r,{cN:"keyword",b:/\$this\b/},t,{b:/(::|->)+[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*/},{cN:"function",bK:"function",e:/[;{]/,eE:!0,i:"\\$|\\[|%",c:[e.UTM,{cN:"params",b:"\\(",e:"\\)",c:["self",t,e.CBCM,a,n]}]},{cN:"class",bK:"class interface",e:"{",eE:!0,i:/[:\(\$"]/,c:[{bK:"extends implements"},e.UTM]},{bK:"namespace",e:";",i:/[\.']/,c:[e.UTM]},{bK:"use",e:";",c:[e.UTM]},{b:"=>"},a,n]}}),e.registerLanguage("python",function(e){var t={keyword:"and elif is global as in if from raise for except finally print import pass return exec else break not with class assert yield try while continue del or def lambda async await nonlocal|10 None True False",built_in:"Ellipsis NotImplemented"},r={cN:"meta",b:/^(>>>|\.\.\.) /},a={cN:"subst",b:/\{/,e:/\}/,k:t,i:/#/},n={cN:"string",c:[e.BE],v:[{b:/(u|b)?r?'''/,e:/'''/,c:[r],r:10},{b:/(u|b)?r?"""/,e:/"""/,c:[r],r:10},{b:/(fr|rf|f)'''/,e:/'''/,c:[r,a]},{b:/(fr|rf|f)"""/,e:/"""/,c:[r,a]},{b:/(u|r|ur)'/,e:/'/,r:10},{b:/(u|r|ur)"/,e:/"/,r:10},{b:/(b|br)'/,e:/'/},{b:/(b|br)"/,e:/"/},{b:/(fr|rf|f)'/,e:/'/,c:[a]},{b:/(fr|rf|f)"/,e:/"/,c:[a]},e.ASM,e.QSM]},i={cN:"number",r:0,v:[{b:e.BNR+"[lLjJ]?"},{b:"\\b(0o[0-7]+)[lLjJ]?"},{b:e.CNR+"[lLjJ]?"}]},s={cN:"params",b:/\(/,e:/\)/,c:["self",r,i,n]};return a.c=[n,i,r],{aliases:["py","gyp"],k:t,i:/(<\/|->|\?)|=>/,c:[r,i,n,e.HCM,{v:[{cN:"function",bK:"def"},{cN:"class",bK:"class"}],e:/:/,i:/[${=;\n,]/,c:[e.UTM,s,{b:/->/,eW:!0,k:"None"}]},{cN:"meta",b:/^[\t ]*@/,e:/$/},{b:/\b(print|exec)\(/}]}}),e.registerLanguage("ruby",function(e){ +var t="[a-zA-Z_]\\w*[!?=]?|[-+~]\\@|<<|>>|=~|===?|<=>|[<>]=?|\\*\\*|[-/+%^&*~`|]|\\[\\]=?",r={keyword:"and then defined module in return redo if BEGIN retry end for self when next until do begin unless END rescue else break undef not super class case require yield alias while ensure elsif or include attr_reader attr_writer attr_accessor",literal:"true false nil"},a={cN:"doctag",b:"@[A-Za-z]+"},n={b:"#<",e:">"},i=[e.C("#","$",{c:[a]}),e.C("^\\=begin","^\\=end",{c:[a],r:10}),e.C("^__END__","\\n$")],s={cN:"subst",b:"#\\{",e:"}",k:r},c={cN:"string",c:[e.BE,s],v:[{b:/'/,e:/'/},{b:/"/,e:/"/},{b:/`/,e:/`/},{b:"%[qQwWx]?\\(",e:"\\)"},{b:"%[qQwWx]?\\[",e:"\\]"},{b:"%[qQwWx]?{",e:"}"},{b:"%[qQwWx]?<",e:">"},{b:"%[qQwWx]?/",e:"/"},{b:"%[qQwWx]?%",e:"%"},{b:"%[qQwWx]?-",e:"-"},{b:"%[qQwWx]?\\|",e:"\\|"},{b:/\B\?(\\\d{1,3}|\\x[A-Fa-f0-9]{1,2}|\\u[A-Fa-f0-9]{4}|\\?\S)\b/},{b:/<<(-?)\w+$/,e:/^\s*\w+$/}]},o={cN:"params",b:"\\(",e:"\\)",endsParent:!0,k:r},l=[c,n,{cN:"class",bK:"class module",e:"$|;",i:/=/,c:[e.inherit(e.TM,{b:"[A-Za-z_]\\w*(::\\w+)*(\\?|\\!)?"}),{b:"<\\s*",c:[{b:"("+e.IR+"::)?"+e.IR}]}].concat(i)},{cN:"function",bK:"def",e:"$|;",c:[e.inherit(e.TM,{b:t}),o].concat(i)},{b:e.IR+"::"},{cN:"symbol",b:e.UIR+"(\\!|\\?)?:",r:0},{cN:"symbol",b:":(?!\\s)",c:[c,{b:t}],r:0},{cN:"number",b:"(\\b0[0-7_]+)|(\\b0x[0-9a-fA-F_]+)|(\\b[1-9][0-9_]*(\\.[0-9_]+)?)|[0_]\\b",r:0},{b:"(\\$\\W)|((\\$|\\@\\@?)(\\w+))"},{cN:"params",b:/\|/,e:/\|/,k:r},{b:"("+e.RSR+"|unless)\\s*",k:"unless",c:[n,{cN:"regexp",c:[e.BE,s],i:/\n/,v:[{b:"/",e:"/[a-z]*"},{b:"%r{",e:"}[a-z]*"},{b:"%r\\(",e:"\\)[a-z]*"},{b:"%r!",e:"![a-z]*"},{b:"%r\\[",e:"\\][a-z]*"}]}].concat(i),r:0}].concat(i);s.c=l,o.c=l;var u="[>?]>",d="[\\w#]+\\(\\w+\\):\\d+:\\d+>",b="(\\w+-)?\\d+\\.\\d+\\.\\d(p\\d+)?[^>]+>",p=[{b:/^\s*=>/,starts:{e:"$",c:l}},{cN:"meta",b:"^("+u+"|"+d+"|"+b+")",starts:{e:"$",c:l}}];return{aliases:["rb","gemspec","podspec","thor","irb"],k:r,i:/\/\*/,c:i.concat(p).concat(l)}}),e.registerLanguage("shell",function(e){return{aliases:["console"],c:[{cN:"meta",b:"^\\s{0,3}[\\w\\d\\[\\]()@-]*[>%$#]",starts:{e:"$",sL:"bash"}}]}}),e.registerLanguage("sql",function(e){var t=e.C("--","$");return{cI:!0,i:/[<>{}*#]/,c:[{bK:"begin end start commit rollback savepoint lock alter create drop rename call delete do handler insert load replace select truncate update set show pragma grant merge describe use explain help declare prepare execute deallocate release unlock purge reset change stop analyze cache flush optimize repair kill install uninstall checksum restore check backup revoke comment",e:/;/,eW:!0,l:/[\w\.]+/,k:{keyword:"abort abs absolute acc acce accep accept access accessed accessible account acos action activate add addtime admin administer advanced advise aes_decrypt aes_encrypt after agent aggregate ali alia alias allocate allow alter always analyze ancillary and any anydata anydataset anyschema anytype apply archive archived archivelog are as asc ascii asin assembly assertion associate asynchronous at atan atn2 attr attri attrib attribu attribut attribute attributes audit authenticated authentication authid authors auto autoallocate autodblink autoextend automatic availability avg backup badfile basicfile before begin beginning benchmark between bfile bfile_base big bigfile bin binary_double binary_float binlog bit_and bit_count bit_length bit_or bit_xor bitmap blob_base block blocksize body both bound buffer_cache buffer_pool build bulk by byte byteordermark bytes cache caching call calling cancel capacity cascade cascaded case cast catalog category ceil ceiling chain change changed char_base char_length character_length characters characterset charindex charset charsetform charsetid check checksum checksum_agg child choose chr chunk class cleanup clear client clob clob_base clone close cluster_id cluster_probability cluster_set clustering coalesce coercibility col collate collation collect colu colum column column_value columns columns_updated comment commit compact compatibility compiled complete composite_limit compound compress compute concat concat_ws concurrent confirm conn connec connect connect_by_iscycle connect_by_isleaf connect_by_root connect_time connection consider consistent constant constraint constraints constructor container content contents context contributors controlfile conv convert convert_tz corr corr_k corr_s corresponding corruption cos cost count count_big counted covar_pop covar_samp cpu_per_call cpu_per_session crc32 create creation critical cross cube cume_dist curdate current current_date current_time current_timestamp current_user cursor curtime customdatum cycle data database databases datafile datafiles datalength date_add date_cache date_format date_sub dateadd datediff datefromparts datename datepart datetime2fromparts day day_to_second dayname dayofmonth dayofweek dayofyear days db_role_change dbtimezone ddl deallocate declare decode decompose decrement decrypt deduplicate def defa defau defaul default defaults deferred defi defin define degrees delayed delegate delete delete_all delimited demand dense_rank depth dequeue des_decrypt des_encrypt des_key_file desc descr descri describ describe descriptor deterministic diagnostics difference dimension direct_load directory disable disable_all disallow disassociate discardfile disconnect diskgroup distinct distinctrow distribute distributed div do document domain dotnet double downgrade drop dumpfile duplicate duration each edition editionable editions element ellipsis else elsif elt empty enable enable_all enclosed encode encoding encrypt end end-exec endian enforced engine engines enqueue enterprise entityescaping eomonth error errors escaped evalname evaluate event eventdata events except exception exceptions exchange exclude excluding execu execut execute exempt exists exit exp expire explain export export_set extended extent external external_1 external_2 externally extract failed failed_login_attempts failover failure far fast feature_set feature_value fetch field fields file file_name_convert filesystem_like_logging final finish first first_value fixed flash_cache flashback floor flush following follows for forall force form forma format found found_rows freelist freelists freepools fresh from from_base64 from_days ftp full function general generated get get_format get_lock getdate getutcdate global global_name globally go goto grant grants greatest group group_concat group_id grouping grouping_id groups gtid_subtract guarantee guard handler hash hashkeys having hea head headi headin heading heap help hex hierarchy high high_priority hosts hour http id ident_current ident_incr ident_seed identified identity idle_time if ifnull ignore iif ilike ilm immediate import in include including increment index indexes indexing indextype indicator indices inet6_aton inet6_ntoa inet_aton inet_ntoa infile initial initialized initially initrans inmemory inner innodb input insert install instance instantiable instr interface interleaved intersect into invalidate invisible is is_free_lock is_ipv4 is_ipv4_compat is_not is_not_null is_used_lock isdate isnull isolation iterate java join json json_exists keep keep_duplicates key keys kill language large last last_day last_insert_id last_value lax lcase lead leading least leaves left len lenght length less level levels library like like2 like4 likec limit lines link list listagg little ln load load_file lob lobs local localtime localtimestamp locate locator lock locked log log10 log2 logfile logfiles logging logical logical_reads_per_call logoff logon logs long loop low low_priority lower lpad lrtrim ltrim main make_set makedate maketime managed management manual map mapping mask master master_pos_wait match matched materialized max maxextents maximize maxinstances maxlen maxlogfiles maxloghistory maxlogmembers maxsize maxtrans md5 measures median medium member memcompress memory merge microsecond mid migration min minextents minimum mining minus minute minvalue missing mod mode model modification modify module monitoring month months mount move movement multiset mutex name name_const names nan national native natural nav nchar nclob nested never new newline next nextval no no_write_to_binlog noarchivelog noaudit nobadfile nocheck nocompress nocopy nocycle nodelay nodiscardfile noentityescaping noguarantee nokeep nologfile nomapping nomaxvalue nominimize nominvalue nomonitoring none noneditionable nonschema noorder nopr nopro noprom nopromp noprompt norely noresetlogs noreverse normal norowdependencies noschemacheck noswitch not nothing notice notrim novalidate now nowait nth_value nullif nulls num numb numbe nvarchar nvarchar2 object ocicoll ocidate ocidatetime ociduration ociinterval ociloblocator ocinumber ociref ocirefcursor ocirowid ocistring ocitype oct octet_length of off offline offset oid oidindex old on online only opaque open operations operator optimal optimize option optionally or oracle oracle_date oradata ord ordaudio orddicom orddoc order ordimage ordinality ordvideo organization orlany orlvary out outer outfile outline output over overflow overriding package pad parallel parallel_enable parameters parent parse partial partition partitions pascal passing password password_grace_time password_lock_time password_reuse_max password_reuse_time password_verify_function patch path patindex pctincrease pctthreshold pctused pctversion percent percent_rank percentile_cont percentile_disc performance period period_add period_diff permanent physical pi pipe pipelined pivot pluggable plugin policy position post_transaction pow power pragma prebuilt precedes preceding precision prediction prediction_cost prediction_details prediction_probability prediction_set prepare present preserve prior priority private private_sga privileges procedural procedure procedure_analyze processlist profiles project prompt protection public publishingservername purge quarter query quick quiesce quota quotename radians raise rand range rank raw read reads readsize rebuild record records recover recovery recursive recycle redo reduced ref reference referenced references referencing refresh regexp_like register regr_avgx regr_avgy regr_count regr_intercept regr_r2 regr_slope regr_sxx regr_sxy reject rekey relational relative relaylog release release_lock relies_on relocate rely rem remainder rename repair repeat replace replicate replication required reset resetlogs resize resource respect restore restricted result result_cache resumable resume retention return returning returns reuse reverse revoke right rlike role roles rollback rolling rollup round row row_count rowdependencies rowid rownum rows rtrim rules safe salt sample save savepoint sb1 sb2 sb4 scan schema schemacheck scn scope scroll sdo_georaster sdo_topo_geometry search sec_to_time second section securefile security seed segment select self sequence sequential serializable server servererror session session_user sessions_per_user set sets settings sha sha1 sha2 share shared shared_pool short show shrink shutdown si_averagecolor si_colorhistogram si_featurelist si_positionalcolor si_stillimage si_texture siblings sid sign sin size size_t sizes skip slave sleep smalldatetimefromparts smallfile snapshot some soname sort soundex source space sparse spfile split sql sql_big_result sql_buffer_result sql_cache sql_calc_found_rows sql_small_result sql_variant_property sqlcode sqldata sqlerror sqlname sqlstate sqrt square standalone standby start starting startup statement static statistics stats_binomial_test stats_crosstab stats_ks_test stats_mode stats_mw_test stats_one_way_anova stats_t_test_ stats_t_test_indep stats_t_test_one stats_t_test_paired stats_wsr_test status std stddev stddev_pop stddev_samp stdev stop storage store stored str str_to_date straight_join strcmp strict string struct stuff style subdate subpartition subpartitions substitutable substr substring subtime subtring_index subtype success sum suspend switch switchoffset switchover sync synchronous synonym sys sys_xmlagg sysasm sysaux sysdate sysdatetimeoffset sysdba sysoper system system_user sysutcdatetime table tables tablespace tan tdo template temporary terminated tertiary_weights test than then thread through tier ties time time_format time_zone timediff timefromparts timeout timestamp timestampadd timestampdiff timezone_abbr timezone_minute timezone_region to to_base64 to_date to_days to_seconds todatetimeoffset trace tracking transaction transactional translate translation treat trigger trigger_nestlevel triggers trim truncate try_cast try_convert try_parse type ub1 ub2 ub4 ucase unarchived unbounded uncompress under undo unhex unicode uniform uninstall union unique unix_timestamp unknown unlimited unlock unpivot unrecoverable unsafe unsigned until untrusted unusable unused update updated upgrade upped upper upsert url urowid usable usage use use_stored_outlines user user_data user_resources users using utc_date utc_timestamp uuid uuid_short validate validate_password_strength validation valist value values var var_samp varcharc vari varia variab variabl variable variables variance varp varraw varrawc varray verify version versions view virtual visible void wait wallet warning warnings week weekday weekofyear wellformed when whene whenev wheneve whenever where while whitespace with within without work wrapped xdb xml xmlagg xmlattributes xmlcast xmlcolattval xmlelement xmlexists xmlforest xmlindex xmlnamespaces xmlpi xmlquery xmlroot xmlschema xmlserialize xmltable xmltype xor year year_to_month years yearweek",literal:"true false null",built_in:"array bigint binary bit blob boolean char character date dec decimal float int int8 integer interval number numeric real record serial serial8 smallint text varchar varying void"},c:[{cN:"string",b:"'",e:"'",c:[e.BE,{b:"''"}]},{cN:"string",b:'"',e:'"',c:[e.BE,{b:'""'}]},{cN:"string",b:"`",e:"`",c:[e.BE]},e.CNM,e.CBCM,t]},e.CBCM,t]}}),e}); \ No newline at end of file diff --git a/Telegram/Resources/iv_html/page.css b/Telegram/Resources/iv_html/page.css new file mode 100644 index 0000000000..b5feac0737 --- /dev/null +++ b/Telegram/Resources/iv_html/page.css @@ -0,0 +1,871 @@ +body { + font-family: 'Helvetica Neue'; + font-size: 17px; + line-height: 25px; + padding: 0; + margin: 0; +} +article { + padding-bottom: 12px; + overflow: hidden; + white-space: pre-wrap; + max-width: 732px; + margin: 0 auto; +} +article h1, +article h2 { + font-family: 'Georgia'; + font-size: 28px; + line-height: 31px; + margin: 21px 18px 12px; + font-weight: normal; + min-height: 31px; +} +article h2 { + font-size: 24px; + line-height: 30px; + margin: -6px 18px 12px; + color: #777; +} +article h6.kicker { + font-family: 'Helvetica Neue'; + font-size: 14px; + line-height: 17px; + margin: 21px 18px 12px; + font-weight: 500; + color: #79828B; +} +article h6.kicker + h1 { + margin-top: 12px; +} +article address { + font-size: 15px; + color: #79828B; + margin: 12px 18px 21px; + font-style: normal; +} +article.rtl address { + direction: ltr; + text-align: right; +} +article address figure { + width: 25px; + height: 25px; + float: right; + margin: 0 0 0 12px; + background: no-repeat center; + background-size: cover; + border-radius: 50%; +} +article address a, +article address a[href] { + color: #79828B; +} +article address a[href] { + text-decoration: underline; +} +article a[href] { + color: #007EE5; + text-decoration: none; +} +article span.reference { + border: dotted #ddd; + border-width: 1px 1px 1px 2px; + background: rgba(255, 255, 255, 0.7); + margin: 0 1px; + padding: 2px; + position: relative; +} +article.rtl span.reference { + border-width: 1px 0 1px 1px; +} +article code { + font-size: 0.94em; + background: #eee; + border-radius: 2px; + padding: 0 3px 1px; +} +article mark { + background: #fcf8e3; + border-radius: 2px; + padding: 0 3px 1px; +} +article sup, +article sub { + font-size: 0.75em; + line-height: 1; +} +article p { + margin: 0 18px 12px; + word-wrap: break-word; +} +article ul p, +article ol p { + margin: 0 0 6px; +} +article pre, +article pre.hljs { + font-family: Menlo; + margin: 14px 0; + padding: 7px 18px; + background: #F5F8FC; + font-size: 16px; + white-space: pre-wrap; + word-wrap: break-word; + overflow-x: visible; + position: relative; +} +article ul pre, +article ol pre, +article ul pre.hljs, +article ol pre.hljs { + margin: 6px 0 6px -18px; +} +article.rtl ul pre, +article.rtl ol pre, +article.rtl ul pre.hljs, +article.rtl ol pre.hljs { + margin-right: -18px; + margin-left: 0; +} +article pre + pre { + margin-top: -14px; +} +article h3, +article h4 { + font-family: 'Georgia'; + font-size: 24px; + line-height: 30px; + margin: 18px 18px 9px; + font-weight: normal; +} +article h4 { + font-size: 19px; + margin: 18px 18px 7px; +} +article ul h3, +article ol h3 { + margin: 12px 0 7px; +} +article ul h4, +article ol h4 { + margin: 10px 0 5px; +} +article blockquote { + font-family: 'Georgia'; + margin: 18px 18px 16px; + padding-left: 22px; + position: relative; + font-style: italic; + word-wrap: break-word; +} +article blockquote:before { + content: ''; + position: absolute; + left: 1px; + top: 3px; + bottom: 3px; + width: 3px; + background-color: #000; + border-radius: 3px; +} +article.rtl blockquote { + padding-right: 22px; + padding-left: 0; +} +article.rtl blockquote:before { + right: 1px; + left: auto; +} +article aside { + font-family: 'Georgia'; + margin: 18px 18px 16px; + padding: 0 18px; + text-align: center; + font-style: italic; +} +article ul blockquote, +article ol blockquote, +article ul aside, +article ol aside { + margin: 12px 0 10px; +} +article blockquote cite, +article aside cite, +article footer cite, +article .iv-pullquote cite { + font-family: 'Helvetica Neue'; + font-size: 15px; + display: block; + color: #79828B; + line-height: 19px; + padding: 5px 0 2px; + font-style: normal; +} +article hr { + width: 50%; + margin: 36px auto 26px; + padding: 2px 0 10px; + border: none; +} +article ul hr, +article ol hr { + margin: 18px auto; +} +article hr:before { + content: ''; + display: block; + border-top: 1px solid #c9cdd1; + padding: 0 0 2px; +} +article footer hr { + margin: 18px auto 6px; +} +article ul, +article ol { + margin: 0 18px 12px; + padding-left: 18px; +} +article.rtl ul, +article.rtl ol { + padding-right: 18px; + padding-left: 0; +} +/*article ul { + list-style: none; +}*/ +article ul > li, +article ol > li { + padding-left: 4px; +} +article.rtl ul > li, +article.rtl ol > li { + padding-right: 4px; + padding-left: 0; +} +/*article ul > li { + position: relative; +} +article ul > li:before { + content: '\2022'; + position: absolute; + display: block; + font-size: 163%; + left: -19px; + top: 1px; +} +article.rtl ul > li:before { + left: auto; + right: -19px; +}*/ +article ul ul, +article ul ol, +article ol ul, +article ol ol { + margin: 0 0 12px; +} + +article table { + width: 100%; + border-collapse: collapse; +} +article table.bordered, +article table.bordered td, +article table.bordered th { + border: 1px solid #ddd; +} +article table.striped tr:nth-child(odd) td { + background-color: #f7f7f7; +} +article table caption { + font-size: 15px; + line-height: 18px; + margin: 4px 0 7px; + text-align: left; + color: #79828B; +} +article.rtl table caption { + text-align: right; +} +article td, +article th { + font-size: 15px; + line-height: 21px; + padding: 6px 5px 5px; + background-color: #fff; + vertical-align: middle; + font-weight: normal; + text-align: left; +} +article th { + background-color: #efefef; +} +article.rtl table td, +article.rtl table th { + text-align: right; +} +article details { + position: relative; + margin: 0 0 12px; + padding: 0 0 1px; +} +article details:before { + content: ''; + display: block; + border-bottom: 1px solid #c8c7cb; + position: absolute; + left: 18px; + right: 0; + bottom: 0; +} +article.rtl details:before { + right: 18px; + left: 0; +} +article details + details { + margin-top: -12px; +} +article details > details:last-child { + margin-bottom: -1px; +} +article summary { + padding: 10px 18px 10px 42px; + line-height: 25px; + min-height: 25px; +} +article.rtl summary { + padding-left: 18px; + padding-right: 42px; +} +article summary:hover { + cursor: pointer; +} +article summary:focus { + outline: none; +} +article summary::-webkit-details-marker { + display: none; +} +article summary::marker { + content: ''; +} +article summary:before { + content: ''; + background: url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAwAAAAICAYAAADN5B7xAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAH1JREFUeNqEjUEKgCAQRSfrNi1bdZFadJjsMC46SSAIHqjB5mcFqdFfhD3eUyKZtb6ln92O2janmXdvrRu+ZTfAgasu1jAHU4qiHAwc/Ff4oCQKsxxZ0NT33XrxUTjkWvgiXFf3TWkU6Vt+XihH515yFiQRpfLnEMUw3yHAABZNTT9emBrvAAAAAElFTkSuQmCC'); + transition: all .2s ease; + display: inline-block; + position: absolute; + width: 12px; + height: 8px; + left: 18px; + top: 18px; +} +article.rtl summary:before { + right: 18px; + left: auto; +} +@media (-webkit-min-device-pixel-ratio: 2), (min-resolution: 192dpi) { + article summary:before { + background: url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABgAAAAQCAYAAAAMJL+VAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAPxJREFUeNq8lEESgiAUhgFbZ0epSW28gB2pZbrrSukBHDWto1TrwHih45AiaDOxesLP9w1PBlzXNfrLSNPqkGWV8ysHGMBqv4mAlyFC7MRPk+T51Z0Lh73AAJZgIoRFUR/bEMb4TggJPG9TTIUzxmIuWHWzOCLfQQgwRiedRMBpIsObFvn+NgSTLEE2bCiKm6eDQ0bAkS2v4AjYuPvJcqtEu9DDshaB665zFZzSV6yCfyr5JplLTOA9wZiEg/a+72Qic9nxubMOPijQSZraCK4UjEiezSVYmsBHBSrJAEIJ1wr0knG4kUAt0cONBX2JGXzGi1uG7SNmOt4CDADc4r+K4txg+wAAAABJRU5ErkJggg=='); + background-size: 12px 8px; + } +} +article details[open] > summary:before { + /*transform: rotateZ(-180deg);*/ + transform: scaleY(-1); +} +article li summary { + padding-left: 24px; +} +article li details:before, +article li summary:before { + left: 0; +} + +img, +video, +iframe { + max-width: 100%; + max-height: 400px; + vertical-align: top; +} +video { + width: 100%; +} +audio { + width: 100%; + width: calc(100% - 36px); + margin: 0 18px; + vertical-align: top; +} +img { + font-size: 12px; + line-height: 14px; + color: #999; +} +img.pic { + max-height: none; + font-size: inherit; + vertical-align: middle; + position: relative; + top: -0.1em; +} +img.pic.optional { + opacity: 0.4; +} +body:hover img.pic.optional { + opacity: 1; +} +iframe.autosize { + max-height: none; +} +.iframe-wrap { + max-width: 100%; + vertical-align: top; + display: inline-block; + position: relative; +} +.iframe-wrap iframe { + position: absolute; + width: 100%; + height: 100%; + top: 0; + left: 0; +} +figure { + margin: 0 0 16px; + padding: 0; + text-align: center; + position: relative; +} +figure.nowide { + margin-left: 18px; + margin-right: 18px; +} +figure.nowide figcaption { + padding-left: 0; + padding-right: 0; +} +ul figure.nowide, +ol figure.nowide { + margin: 0 0 12px; +} +figure > figure { + margin: 0; +} +figcaption { + font-size: 15px; + color: #79828B; + padding: 6px 18px 0; + line-height: 19px; + text-align: left; +} +article.rtl figcaption { + text-align: right; +} +ul figcaption, +ol figcaption { + padding-left: 0; + padding-right: 0; +} +figcaption > cite { + font-family: 'Helvetica Neue'; + font-size: 12px; + display: block; + line-height: 15px; + padding: 2px 0 0; + font-style: normal; +} +footer { + margin: 12px 18px; + color: #79828B; +} + +figure.slideshow-wrap { + position: relative; +} +figure.slideshow { + position: relative; + white-space: nowrap; + width: 100%; + background: #000; + overflow: hidden; +} +figure.slideshow > figure { + position: static !important; + display: inline-block; + width: 100%; + vertical-align: middle; + transition: margin .3s; +} +figure.slideshow > figure figcaption { + box-sizing: border-box; + position: absolute; + bottom: 0; + width: 100%; + padding-bottom: 36px; +} +figure.slideshow > figure figcaption:after { + content: ''; + display: block; + position: absolute; + left: 0; + right: 0; + bottom: 0; + top: -75px; + background: -moz-linear-gradient(top,rgba(64,64,64,0),rgba(64,64,64,.55)); + background: -webkit-gradient(linear,0 0,0 100%,from(rgba(64,64,64,0)),to(rgba(64,64,64,.55))); + background: -o-linear-gradient(rgba(64,64,64,0),rgba(64,64,64,.55)); + pointer-events: none; +} +figure.slideshow > figure figcaption > span, +figure.slideshow > figure figcaption > cite { + position: relative; + color: #fff; + text-shadow: 0 1px rgba(0, 0, 0, .4); + z-index: 1; + display: block; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} +figure.slideshow > figure figcaption > span { + display: -webkit-box; + max-height: 3.8em; + -webkit-line-clamp: 3; + -webkit-box-orient: vertical; + white-space: pre-wrap; +} +figure.slideshow > figure figcaption code { + text-shadow: none; + background: rgba(204, 204, 204, .7); + color: #fff; +} +figure.slideshow > figure figcaption mark { + text-shadow: none; + background: rgba(33, 123, 134, .7); + color: #fff; +} +figure.slideshow > figure figcaption a, +figure.slideshow > figure figcaption a:hover { + color: #66baff; +} +.slideshow-buttons { + position: absolute; + width: 100%; + bottom: 10px; + white-space: nowrap; + overflow: hidden; + z-index: 3; +} +.slideshow-buttons > fieldset { + padding: 0 10px 20px; + margin: 0 0 -20px; + border: none; + line-height: 0; + overflow: hidden; + overflow-x: auto; + min-width: auto; +} +.slideshow-buttons label { + display: inline-block; + padding: 7px; + cursor: pointer; +} +.slideshow-buttons input { + position: absolute; + left: -10000px; +} +.slideshow-buttons label i { + display: inline-block; + background: #fff; + box-shadow: 0 0 3px rgba(0, 0, 0, .4); + border-radius: 3.5px; + width: 7px; + height: 7px; + opacity: .6; + transition: opacity .3s; +} +.slideshow-buttons input:checked ~ i { + opacity: 1; +} + +figure.collage { + margin: -2px 16px; + text-align: left; +} +figure.collage > figure { + display: inline-block; + vertical-align: top; + width: calc(25% - 4px); + margin: 2px; + box-sizing: border-box; +} +figure.collage > figure > i { + background: no-repeat center; + background-size: cover; + display: inline-block; + vertical-align: top; + width: 100%; + padding-top: 100%; +} + +figure.table-wrap { + overflow: auto; + -webkit-overflow-scrolling: touch; +} +figure.table { + display: table-cell; + padding: 0 18px; +} +article ol figure.table-wrap, +article ul figure.table-wrap { + margin-top: 7px; +} +article ol figure.table, +article ul figure.table { + padding: 0; +} + +figure blockquote.embed-post { + text-align: left; + margin-bottom: 0; +} +article.rtl figure blockquote.embed-post { + text-align: right; +} +blockquote.embed-post address { + margin: 0; + padding: 5px 0 9px; + overflow: hidden; +} +blockquote.embed-post address figure { + width: 50px; + height: 50px; + float: left; + margin: 0 12px 0 0; + background: no-repeat center; + background-size: cover; + border-radius: 50%; +} +article.rtl blockquote.embed-post address figure { + float: right; + margin-left: 12px; + margin-right: 0; +} +blockquote.embed-post address a { + display: inline-block; + padding-top: 2px; + font-size: 17px; + font-weight: 600; + color: #000; +} +blockquote.embed-post address time { + display: block; + line-height: 19px; +} +blockquote.embed-post p, +blockquote.embed-post blockquote { + margin: 0 0 7px; + clear: left; +} +blockquote.embed-post figcaption { + padding-left: 0; + padding-right: 0; +} +blockquote.embed-post figure.collage { + margin-left: -2px; + margin-right: -2px; +} +blockquote.embed-post footer { + margin: 12px 0 0; + font-style: normal; +} +blockquote.embed-post footer hr { + display: none; +} + +section.embed-post { + display: block; + width: auto; + height: auto; + background: #f7f7f7; + margin: 0 18px 12px; + padding: 24px 18px; + text-align: center; +} +section.embed-post strong { + font-size: 21px; + font-weight: normal; + display: block; + color: #777; +} +section.embed-post small { + display: block; + color: #777; +} + +section.related { + margin: 7px 0 12px; +} +section.related h4 { + font-family: 'Helvetica Neue'; + font-size: 17px; + line-height: 26px; + font-weight: 500; + display: block; + padding: 7px 18px; + background: #f7f7f7; + margin: 0; + color: #000; +} +section.related a.related-link { + display: block; + padding: 15px 18px 16px; + background: #fff; + position: relative; + overflow: hidden; +} +section.related a.related-link:after { + content: ''; + display: block; + border-bottom: 1px solid #c8c7cb; + position: absolute; + left: 18px; + right: 0; + bottom: 0; +} +section.related .related-link-url { + display: block; + font-size: 15px; + line-height: 18px; + padding: 7px 0; + color: #999; + word-break: break-word; +} +section.related .related-link-thumb { + display: inline-block; + float: right; + width: 87px; + height: 87px; + border-radius: 4px; + background: no-repeat center; + background-size: cover; + margin-left: 15px; +} +section.related .related-link-content { + display: block; + margin: -3px 0; +} +section.related .related-link-title { + font-size: 15px; + font-weight: 500; + line-height: 18px; + display: block; + display: -webkit-box; + margin-bottom: 4px; + max-height: 36px; + -webkit-line-clamp: 2; + -webkit-box-orient: vertical; + overflow: hidden; + text-overflow: ellipsis; + white-space: pre-wrap; + color: #000; +} +section.related .related-link-desc { + font-size: 14px; + line-height: 17px; + display: block; + display: -webkit-box; + max-height: 51px; + -webkit-line-clamp: 3; + -webkit-box-orient: vertical; + overflow: hidden; + text-overflow: ellipsis; + white-space: pre-wrap; + color: #000; +} +section.related .related-link-source { + font-size: 13px; + line-height: 17px; + display: block; + overflow: hidden; + margin-top: 4px; + text-overflow: ellipsis; + white-space: nowrap; + color: #818181; +} + +section.message { + position: absolute; + display: table; + width: 100%; + height: 100%; +} +section.message.static { + position: static; + min-height: 200px; + height: 100vh; +} +section.message > aside { + display: table-cell; + vertical-align: middle; + text-align: center; + color: #999; + font-size: 24px; + pointer-events: none; +} +section.message > aside > cite { + display: block; + font-size: 14px; + padding: 10px 0 0; + font-style: normal; + color: #ccc; +} + +section.channel { + margin-top: -16px; + margin-bottom: -9px; +} +section.channel:first-child { + margin-top: 0; +} +section.channel > a { + display: block; + padding: 7px 18px; + background: #f7f7f7; +} +section.channel > a:before { + content: 'Join'; + color: #3196e8; + font-weight: 500; + margin-left: 7px; + float: right; +} +section.channel > a > h4 { + font-family: 'Helvetica Neue'; + font-size: 17px; + line-height: 26px; + font-weight: 500; + margin: 0; + color: #000; + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; +} + +.iv-pullquote { + text-align: center; + max-width: 420px; + font-size: 19px; + display: block; + margin: 0 auto; +} +.iv-photo-wrap { + width: 100%; + background-size: 100%; + margin: 0 auto; +} +.iv-photo { + background-size: 100%; +} diff --git a/Telegram/Resources/iv_html/page.js b/Telegram/Resources/iv_html/page.js new file mode 100644 index 0000000000..d821a1e434 --- /dev/null +++ b/Telegram/Resources/iv_html/page.js @@ -0,0 +1,86 @@ +var IV = { + sendPostMessage: function(data) { + try { + window.parent.postMessage(JSON.stringify(data), window.parentOrigin); + } catch(e) {} + }, + frameClickHandler: function(e) { + var target = e.target, href; + do { + if (target.tagName == 'SUMMARY') return; + if (target.tagName == 'DETAILS') return; + if (target.tagName == 'LABEL') return; + if (target.tagName == 'AUDIO') return; + if (target.tagName == 'A') break; + } while (target = target.parentNode); + if (target && target.hasAttribute('href')) { + var base_loc = document.createElement('A'); + base_loc.href = window.currentUrl; + if (base_loc.origin != target.origin || + base_loc.pathname != target.pathname || + base_loc.search != target.search) { + IV.sendPostMessage({event: 'link_click', url: target.href}); + } + } + e.preventDefault(); + }, + postMessageHandler: function(event) { + if (event.source !== window.parent || + event.origin != window.parentOrigin) { + return; + } + try { + var data = JSON.parse(event.data); + } catch(e) { + var data = {}; + } + }, + slideshowSlide: function(el, next) { + var dir = window.getComputedStyle(el, null).direction || 'ltr'; + var marginProp = dir == 'rtl' ? 'marginRight' : 'marginLeft'; + if (next) { + var s = el.previousSibling.s; + s.value = (+s.value + 1 == s.length) ? 0 : +s.value + 1; + s.forEach(function(el){ el.checked && el.parentNode.scrollIntoView && el.parentNode.scrollIntoView({behavior: 'smooth', block: 'center', inline: 'center'}); }); + el.firstChild.style[marginProp] = (-100 * s.value) + '%'; + } else { + el.form.nextSibling.firstChild.style[marginProp] = (-100 * el.value) + '%'; + } + return false; + }, + initPreBlocks: function() { + if (!hljs) return; + var pres = document.getElementsByTagName('pre'); + for (var i = 0; i < pres.length; i++) { + if (pres[i].hasAttribute('data-language')) { + hljs.highlightBlock(pres[i]); + } + } + }, + initEmbedBlocks: function() { + var iframes = document.getElementsByTagName('iframe'); + for (var i = 0; i < iframes.length; i++) { + (function(iframe) { + window.addEventListener('message', function(event) { + if (event.source !== iframe.contentWindow || + event.origin != window.origin) { + return; + } + try { + var data = JSON.parse(event.data); + } catch(e) { + var data = {}; + } + if (data.eventType == 'resize_frame') { + if (data.eventData.height) { + iframe.style.height = data.eventData.height + 'px'; + } + } + }, false); + })(iframes[i]); + } + } +}; + +document.onclick = IV.frameClickHandler; +window.onmessage = IV.postMessageHandler; diff --git a/Telegram/Resources/qrc/telegram/iv.qrc b/Telegram/Resources/qrc/telegram/iv.qrc new file mode 100644 index 0000000000..4d67c89c7f --- /dev/null +++ b/Telegram/Resources/qrc/telegram/iv.qrc @@ -0,0 +1,8 @@ + + + ../../iv_html/page.css + ../../iv_html/page.js + ../../iv_html/highlight.9.12.0.css + ../../iv_html/highlight.9.12.0.js + + diff --git a/Telegram/SourceFiles/boxes/peers/edit_peer_color_box.cpp b/Telegram/SourceFiles/boxes/peers/edit_peer_color_box.cpp index 2e24d2804c..a658640638 100644 --- a/Telegram/SourceFiles/boxes/peers/edit_peer_color_box.cpp +++ b/Telegram/SourceFiles/boxes/peers/edit_peer_color_box.cpp @@ -33,6 +33,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL #include "info/boosts/info_boosts_widget.h" #include "info/profile/info_profile_emoji_status_panel.h" #include "info/info_memento.h" +#include "iv/iv_data.h" #include "lang/lang_keys.h" #include "lottie/lottie_icon.h" #include "lottie/lottie_single_player.h" @@ -310,6 +311,7 @@ PreviewWrap::PreviewWrap( nullptr, // photo nullptr, // document WebPageCollage(), + nullptr, // iv 0, // duration QString(), // author false, // hasLargeMedia diff --git a/Telegram/SourceFiles/core/application.cpp b/Telegram/SourceFiles/core/application.cpp index 7e7dadbd45..8fe1e75c7d 100644 --- a/Telegram/SourceFiles/core/application.cpp +++ b/Telegram/SourceFiles/core/application.cpp @@ -44,6 +44,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL #include "api/api_updates.h" #include "calls/calls_instance.h" #include "countries/countries_manager.h" +#include "iv/iv_instance.h" #include "lang/lang_file_parser.h" #include "lang/lang_translator.h" #include "lang/lang_cloud_manager.h" @@ -162,6 +163,7 @@ Application::Application() , _domain(std::make_unique(cDataFile())) , _exportManager(std::make_unique()) , _calls(std::make_unique()) +, _iv(std::make_unique()) , _langpack(std::make_unique()) , _langCloudManager(std::make_unique(langpack())) , _emojiKeywords(std::make_unique()) @@ -218,6 +220,7 @@ Application::~Application() { // Domain::finish() and there is a violation on Ensures(started()). Payments::CheckoutProcess::ClearAll(); InlineBots::AttachWebView::ClearAll(); + _iv->closeAll(); _domain->finish(); @@ -1272,6 +1275,8 @@ bool Application::hasActiveWindow(not_null session) const { return false; } else if (_calls->hasActivePanel(session)) { return true; + } else if (_iv->hasActiveWindow(session)) { + return true; } else if (const auto window = _lastActiveWindow) { return (window->account().maybeSession() == session) && window->widget()->isActive(); diff --git a/Telegram/SourceFiles/core/application.h b/Telegram/SourceFiles/core/application.h index b06e020743..123d1010a0 100644 --- a/Telegram/SourceFiles/core/application.h +++ b/Telegram/SourceFiles/core/application.h @@ -45,6 +45,10 @@ class Account; class Session; } // namespace Main +namespace Iv { +class Instance; +} // namespace Iv + namespace Ui { namespace Animations { class Manager; @@ -280,6 +284,11 @@ public: return *_calls; } + // Iv. + Iv::Instance &iv() const { + return *_iv; + } + void logout(Main::Account *account = nullptr); void logoutWithChecks(Main::Account *account); void forceLogOut( @@ -409,6 +418,7 @@ private: const std::unique_ptr _domain; const std::unique_ptr _exportManager; const std::unique_ptr _calls; + const std::unique_ptr _iv; base::flat_map< Main::Account*, std::unique_ptr> _primaryWindows; diff --git a/Telegram/SourceFiles/data/data_session.cpp b/Telegram/SourceFiles/data/data_session.cpp index 24ea2cd468..36f35642d0 100644 --- a/Telegram/SourceFiles/data/data_session.cpp +++ b/Telegram/SourceFiles/data/data_session.cpp @@ -36,6 +36,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL #include "media/audio/media_audio.h" #include "boxes/abstract_box.h" #include "passport/passport_form_controller.h" +#include "iv/iv_data.h" #include "lang/lang_keys.h" // tr::lng_deleted(tr::now) in user name #include "data/business/data_business_chatbots.h" #include "data/business/data_business_info.h" @@ -3365,6 +3366,7 @@ not_null Session::processWebpage( nullptr, nullptr, WebPageCollage(), + nullptr, 0, QString(), false, @@ -3389,6 +3391,7 @@ not_null Session::webpage( nullptr, nullptr, WebPageCollage(), + nullptr, 0, QString(), false, @@ -3406,6 +3409,7 @@ not_null Session::webpage( PhotoData *photo, DocumentData *document, WebPageCollage &&collage, + std::unique_ptr iv, int duration, const QString &author, bool hasLargeMedia, @@ -3423,6 +3427,7 @@ not_null Session::webpage( photo, document, std::move(collage), + std::move(iv), duration, author, hasLargeMedia, @@ -3503,6 +3508,14 @@ void Session::webpageApplyFields( }, [](const auto &) {}); } } + if (const auto page = data.vcached_page()) { + for (const auto photo : page->data().vphotos().v) { + processPhoto(photo); + } + for (const auto document : page->data().vdocuments().v) { + processDocument(document); + } + } webpageApplyFields( page, (story ? WebPageType::Story : ParseWebPageType(data)), @@ -3523,6 +3536,9 @@ void Session::webpageApplyFields( ? processDocument(*document).get() : lookupThemeDocument()), WebPageCollage(this, data), + (data.vcached_page() + ? std::make_unique(data, *data.vcached_page()) + : nullptr), data.vduration().value_or_empty(), qs(data.vauthor().value_or_empty()), data.is_has_large_media(), @@ -3541,6 +3557,7 @@ void Session::webpageApplyFields( PhotoData *photo, DocumentData *document, WebPageCollage &&collage, + std::unique_ptr iv, int duration, const QString &author, bool hasLargeMedia, @@ -3557,6 +3574,7 @@ void Session::webpageApplyFields( photo, document, std::move(collage), + std::move(iv), duration, author, hasLargeMedia, diff --git a/Telegram/SourceFiles/data/data_session.h b/Telegram/SourceFiles/data/data_session.h index 74204af26e..b233aead14 100644 --- a/Telegram/SourceFiles/data/data_session.h +++ b/Telegram/SourceFiles/data/data_session.h @@ -38,6 +38,10 @@ namespace Passport { struct SavedCredentials; } // namespace Passport +namespace Iv { +class Data; +} // namespace Iv + namespace Data { class Folder; @@ -581,6 +585,7 @@ public: PhotoData *photo, DocumentData *document, WebPageCollage &&collage, + std::unique_ptr iv, int duration, const QString &author, bool hasLargeMedia, @@ -858,6 +863,7 @@ private: PhotoData *photo, DocumentData *document, WebPageCollage &&collage, + std::unique_ptr iv, int duration, const QString &author, bool hasLargeMedia, diff --git a/Telegram/SourceFiles/data/data_web_page.cpp b/Telegram/SourceFiles/data/data_web_page.cpp index 6174c138bd..9b3f7fd661 100644 --- a/Telegram/SourceFiles/data/data_web_page.cpp +++ b/Telegram/SourceFiles/data/data_web_page.cpp @@ -15,6 +15,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL #include "data/data_channel.h" #include "data/data_document.h" #include "lang/lang_keys.h" +#include "iv/iv_data.h" #include "ui/image/image.h" #include "ui/text/text_entity.h" @@ -206,6 +207,8 @@ WebPageData::WebPageData(not_null owner, const WebPageId &id) , _owner(owner) { } +WebPageData::~WebPageData() = default; + Data::Session &WebPageData::owner() const { return *_owner; } @@ -225,6 +228,7 @@ bool WebPageData::applyChanges( PhotoData *newPhoto, DocumentData *newDocument, WebPageCollage &&newCollage, + std::unique_ptr newIv, int newDuration, const QString &newAuthor, bool newHasLargeMedia, @@ -276,6 +280,7 @@ bool WebPageData::applyChanges( && photo == newPhoto && document == newDocument && collage.items == newCollage.items + && (!iv == !newIv) && duration == newDuration && author == resultAuthor && hasLargeMedia == (newHasLargeMedia ? 1 : 0) @@ -296,6 +301,7 @@ bool WebPageData::applyChanges( photo = newPhoto; document = newDocument; collage = std::move(newCollage); + iv = std::move(newIv); duration = newDuration; author = resultAuthor; pendingTill = newPendingTill; diff --git a/Telegram/SourceFiles/data/data_web_page.h b/Telegram/SourceFiles/data/data_web_page.h index 629ba2bc93..7b4f7db700 100644 --- a/Telegram/SourceFiles/data/data_web_page.h +++ b/Telegram/SourceFiles/data/data_web_page.h @@ -17,6 +17,10 @@ namespace Data { class Session; } // namespace Data +namespace Iv { +class Data; +} // namespace Iv + enum class WebPageType : uint8 { None, @@ -64,6 +68,7 @@ struct WebPageCollage { struct WebPageData { WebPageData(not_null owner, const WebPageId &id); + ~WebPageData(); [[nodiscard]] Data::Session &owner() const; [[nodiscard]] Main::Session &session() const; @@ -79,6 +84,7 @@ struct WebPageData { PhotoData *newPhoto, DocumentData *newDocument, WebPageCollage &&newCollage, + std::unique_ptr newIv, int newDuration, const QString &newAuthor, bool newHasLargeMedia, @@ -105,6 +111,7 @@ struct WebPageData { PhotoData *photo = nullptr; DocumentData *document = nullptr; WebPageCollage collage; + std::unique_ptr iv; int duration = 0; TimeId pendingTill = 0; uint32 version : 30 = 0; diff --git a/Telegram/SourceFiles/history/view/history_view_view_button.cpp b/Telegram/SourceFiles/history/view/history_view_view_button.cpp index 52e9847ae9..aa12fe1c2d 100644 --- a/Telegram/SourceFiles/history/view/history_view_view_button.cpp +++ b/Telegram/SourceFiles/history/view/history_view_view_button.cpp @@ -11,6 +11,8 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL #include "history/history.h" #include "history/history_item_components.h" #include "history/view/history_view_cursor_state.h" +#include "iv/iv_data.h" +#include "iv/iv_controller.h" #include "lang/lang_keys.h" #include "ui/effects/ripple_animation.h" #include "ui/painter.h" @@ -18,6 +20,9 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL #include "window/window_session_controller.h" #include "styles/style_chat.h" +#include "core/application.h" +#include "iv/iv_instance.h" + namespace HistoryView { namespace { diff --git a/Telegram/SourceFiles/history/view/media/history_view_web_page.cpp b/Telegram/SourceFiles/history/view/media/history_view_web_page.cpp index 43b3d83707..5b46381fb9 100644 --- a/Telegram/SourceFiles/history/view/media/history_view_web_page.cpp +++ b/Telegram/SourceFiles/history/view/media/history_view_web_page.cpp @@ -7,6 +7,10 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL */ #include "history/view/media/history_view_web_page.h" +#include "core/application.h" +#include "base/qt/qt_key_modifiers.h" +#include "window/window_session_controller.h" +#include "iv/iv_instance.h" #include "core/click_handler_types.h" #include "core/ui_integration.h" #include "data/data_file_click_handler.h" @@ -82,7 +86,29 @@ constexpr auto kMaxOriginalEntryLines = 8192; return result; } +[[nodiscard]] ClickHandlerPtr IvClickHandler(not_null webpage) { + return std::make_shared([=](ClickContext context) { + const auto my = context.other.value(); + if (const auto controller = my.sessionWindow.get()) { + if (const auto iv = webpage->iv.get()) { +#ifdef _DEBUG + const auto local = base::IsCtrlPressed(); +#else // _DEBUG + const auto local = false; +#endif // _DEBUG + Core::App().iv().show(controller->uiShow(), iv, local); + return; + } else { + HiddenUrlClickHandler::Open(webpage->url, context.other); + } + } + }); +} + [[nodiscard]] QString PageToPhrase(not_null webpage) { + if (webpage->iv) { + return u"Instant View"_q; + } const auto type = webpage->type; return Ui::Text::Upper((type == WebPageType::Theme) ? tr::lng_view_button_theme(tr::now) @@ -118,7 +144,8 @@ constexpr auto kMaxOriginalEntryLines = 8192; [[nodiscard]] bool HasButton(not_null webpage) { const auto type = webpage->type; - return (type == WebPageType::Message) + return webpage->iv + || (type == WebPageType::Message) || (type == WebPageType::Group) || (type == WebPageType::Channel) || (type == WebPageType::ChannelBoost) @@ -245,7 +272,7 @@ QSize WebPage::countOptimalSize() { } return true; }(); - _openl = (previewOfHiddenUrl + _openl = _data->iv ? IvClickHandler(_data) : (previewOfHiddenUrl || UrlClickHandler::IsSuspicious(_data->url)) ? std::make_shared(_data->url) : std::make_shared(_data->url, true); diff --git a/Telegram/SourceFiles/iv/iv_controller.cpp b/Telegram/SourceFiles/iv/iv_controller.cpp new file mode 100644 index 0000000000..bac53f9835 --- /dev/null +++ b/Telegram/SourceFiles/iv/iv_controller.cpp @@ -0,0 +1,115 @@ +/* +This file is part of Telegram Desktop, +the official desktop application for the Telegram messaging service. + +For license and copyright information please follow this link: +https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL +*/ +#include "iv/iv_controller.h" + +#include "iv/iv_data.h" +#include "ui/widgets/rp_window.h" +#include "webview/webview_data_stream_memory.h" +#include "webview/webview_embed.h" +#include "webview/webview_interface.h" + +#include +#include + +namespace Iv { + +Controller::Controller() = default; + +Controller::~Controller() { + _webview = nullptr; + _window = nullptr; +} + +void Controller::show(const QString &dataPath, Prepared page) { + _window = std::make_unique(); + const auto window = _window.get(); + + window->setGeometry({ 200, 200, 800, 600 }); + + const auto container = Ui::CreateChild( + window->body().get()); + window->sizeValue() | rpl::start_with_next([=](QSize size) { + container->setGeometry(QRect(QPoint(), size)); + }, container->lifetime()); + container->show(); + + _webview = std::make_unique( + container, + Webview::WindowConfig{ .userDataPath = dataPath }); + const auto raw = _webview.get(); + + window->lifetime().add([=] { + _webview = nullptr; + }); + if (!raw->widget()) { + _webview = nullptr; + _window = nullptr; + return; + } + raw->widget()->show(); + + container->geometryValue( + ) | rpl::start_with_next([=](QRect geometry) { + raw->widget()->setGeometry(geometry); + }, _lifetime); + + raw->setNavigationStartHandler([=](const QString &uri, bool newWindow) { + return true; + }); + raw->setNavigationDoneHandler([=](bool success) { + }); + raw->setDataRequestHandler([=](Webview::DataRequest request) { + if (!request.id.starts_with("iv/")) { + _dataRequests.fire(std::move(request)); + return Webview::DataResult::Pending; + } + const auto finishWith = [&](QByteArray data, std::string mime) { + request.done({ + .stream = std::make_unique( + std::move(data), + std::move(mime)), + }); + return Webview::DataResult::Done; + }; + const auto id = std::string_view(request.id).substr(3); + if (id == "page.html") { + return finishWith(page.html, "text/html"); + } + const auto css = id.ends_with(".css"); + const auto js = !css && id.ends_with(".js"); + if (!css && !js) { + return Webview::DataResult::Failed; + } + const auto qstring = QString::fromUtf8(id.data(), id.size()); + const auto pattern = u"^[a-zA-Z\\.\\-_0-9]+$"_q; + if (QRegularExpression(pattern).match(qstring).hasMatch()) { + auto file = QFile(u":/iv/"_q + qstring); + if (file.open(QIODevice::ReadOnly)) { + const auto mime = css ? "text/css" : "text/javascript"; + return finishWith(file.readAll(), mime); + } + } + return Webview::DataResult::Failed; + }); + + raw->init(R"( +)"); + raw->navigateToData("iv/page.html"); + + window->show(); +} + +rpl::producer Controller::dataRequests() const { + return _dataRequests.events(); +} + +rpl::lifetime &Controller::lifetime() { + return _lifetime; +} + +} // namespace Iv diff --git a/Telegram/SourceFiles/iv/iv_controller.h b/Telegram/SourceFiles/iv/iv_controller.h new file mode 100644 index 0000000000..b35dfc00a0 --- /dev/null +++ b/Telegram/SourceFiles/iv/iv_controller.h @@ -0,0 +1,42 @@ +/* +This file is part of Telegram Desktop, +the official desktop application for the Telegram messaging service. + +For license and copyright information please follow this link: +https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL +*/ +#pragma once + +namespace Webview { +struct DataRequest; +class Window; +} // namespace Webview + +namespace Ui { +class RpWindow; +} // namespace Ui + +namespace Iv { + +struct Prepared; + +class Controller final { +public: + Controller(); + ~Controller(); + + void show(const QString &dataPath, Prepared page); + + [[nodiscard]] rpl::producer dataRequests() const; + + [[nodiscard]] rpl::lifetime &lifetime(); + +private: + std::unique_ptr _window; + std::unique_ptr _webview; + rpl::event_stream _dataRequests; + rpl::lifetime _lifetime; + +}; + +} // namespace Iv diff --git a/Telegram/SourceFiles/iv/iv_data.cpp b/Telegram/SourceFiles/iv/iv_data.cpp new file mode 100644 index 0000000000..c34424e27c --- /dev/null +++ b/Telegram/SourceFiles/iv/iv_data.cpp @@ -0,0 +1,63 @@ +/* +This file is part of Telegram Desktop, +the official desktop application for the Telegram messaging service. + +For license and copyright information please follow this link: +https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL +*/ +#include "iv/iv_data.h" + +#include "iv/iv_prepare.h" + +namespace Iv { + +QByteArray GeoPointId(Geo point) { + const auto lat = int(point.lat * 1000000); + const auto lon = int(point.lon * 1000000); + const auto combined = (std::uint64_t(std::uint32_t(lat)) << 32) + | std::uint64_t(std::uint32_t(lon)); + return QByteArray::number(combined) + + ',' + + QByteArray::number(point.access); +} + +Geo GeoPointFromId(QByteArray data) { + const auto parts = data.split(','); + if (parts.size() != 2) { + return {}; + } + const auto combined = parts[0].toULongLong(); + const auto lat = int(std::uint32_t(combined >> 32)); + const auto lon = int(std::uint32_t(combined & 0xFFFFFFFFULL)); + return { + .lat = lat / 1000000., + .lon = lon / 1000000., + .access = parts[1].toULongLong(), + }; +} + +Data::Data(const MTPDwebPage &webpage, const MTPPage &page) +: _source(std::make_unique(Source{ + .page = page, + .webpagePhoto = (webpage.vphoto() + ? *webpage.vphoto() + : std::optional()), + .webpageDocument = (webpage.vdocument() + ? *webpage.vdocument() + : std::optional()), +})) { +} + +QString Data::id() const { + return qs(_source->page.data().vurl()); +} + +Data::~Data() = default; + +void Data::prepare(const Options &options, Fn done) const { + crl::async([source = *_source, options, done = std::move(done)] { + done(Prepare(source, options)); + }); +} + +} // namespace Iv diff --git a/Telegram/SourceFiles/iv/iv_data.h b/Telegram/SourceFiles/iv/iv_data.h new file mode 100644 index 0000000000..1eec747eff --- /dev/null +++ b/Telegram/SourceFiles/iv/iv_data.h @@ -0,0 +1,47 @@ +/* +This file is part of Telegram Desktop, +the official desktop application for the Telegram messaging service. + +For license and copyright information please follow this link: +https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL +*/ +#pragma once + +namespace Iv { + +struct Source; + +struct Options { + QString saveToFolder; +}; + +struct Prepared { + QByteArray html; + std::vector resources; + base::flat_map embeds; +}; + +struct Geo { + float64 lat = 0.; + float64 lon = 0.; + uint64 access = 0; +}; + +[[nodiscard]] QByteArray GeoPointId(Geo point); +[[nodiscard]] Geo GeoPointFromId(QByteArray data); + +class Data final { +public: + Data(const MTPDwebPage &webpage, const MTPPage &page); + ~Data(); + + [[nodiscard]] QString id() const; + + void prepare(const Options &options, Fn done) const; + +private: + const std::unique_ptr _source; + +}; + +} // namespace Iv diff --git a/Telegram/SourceFiles/iv/iv_instance.cpp b/Telegram/SourceFiles/iv/iv_instance.cpp new file mode 100644 index 0000000000..27f3dcfb23 --- /dev/null +++ b/Telegram/SourceFiles/iv/iv_instance.cpp @@ -0,0 +1,663 @@ +/* +This file is part of Telegram Desktop, +the official desktop application for the Telegram messaging service. + +For license and copyright information please follow this link: +https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL +*/ +#include "iv/iv_instance.h" + +#include "core/file_utilities.h" +#include "data/data_cloud_file.h" +#include "data/data_document.h" +#include "data/data_file_origin.h" +#include "data/data_photo_media.h" +#include "data/data_session.h" +#include "iv/iv_controller.h" +#include "iv/iv_data.h" +#include "main/main_account.h" +#include "main/main_domain.h" +#include "main/main_session.h" +#include "main/session/session_show.h" +#include "media/streaming/media_streaming_loader.h" +#include "storage/file_download.h" +#include "storage/storage_domain.h" +#include "ui/boxes/confirm_box.h" +#include "webview/webview_data_stream_memory.h" +#include "webview/webview_interface.h" + +namespace Iv { +namespace { + +constexpr auto kGeoPointScale = 1; +constexpr auto kGeoPointZoomMin = 13; +constexpr auto kMaxLoadParts = 3; +constexpr auto kKeepLoadingParts = 8; + +[[nodiscard]] QString LookupLocalPath( + const std::shared_ptr show) { + const auto &domain = show->session().account().domain(); + const auto &base = domain.local().webviewDataPath(); + static auto counter = 0; + return base + u"/iv/"_q + QString::number(++counter); +} + +[[nodiscard]] Storage::Cache::Key IvBaseCacheKey( + not_null document) { + auto big = document->bigFileBaseCacheKey(); + big.low += 0x7FF; + return big; +} + +} // namespace + +class Shown final : public base::has_weak_ptr { +public: + Shown( + std::shared_ptr show, + not_null data, + bool local); + + [[nodiscard]] bool showing( + not_null session, + not_null data) const; + [[nodiscard]] bool showingFrom(not_null session) const; + [[nodiscard]] bool activeFor(not_null session) const; + +private: + struct MapPreview { + std::unique_ptr<::Data::CloudFile> file; + QByteArray bytes; + }; + struct PartRequest { + Webview::DataRequest request; + QByteArray data; + std::vector loaded; + int64 offset = 0; + }; + struct FileLoad { + not_null document; + std::unique_ptr loader; + std::vector requests; + std::string mime; + rpl::lifetime lifetime; + }; + + void showLocal(Prepared result); + void showWindowed(Prepared result); + + // Local. + void showProgress(int index); + void loadResource(int index); + void finishLocal(const QString &path); + [[nodiscard]] QString localRoot() const; + void writeLocal(const QString &relative, const QByteArray &data); + void loadPhoto(QString id, PhotoId photoId); + void loadDocument(QString id, DocumentId documentId); + void loadPage(QString id, QString tag); + void loadMap(QString id, QString params); + void writeEmbed(QString id, QString hash); + + // Windowed. + void streamPhoto(PhotoId photoId, Webview::DataRequest request); + void streamFile(DocumentId documentId, Webview::DataRequest request); + void streamFile(FileLoad &file, Webview::DataRequest request); + void processPartInFile( + FileLoad &file, + Media::Streaming::LoadedPart &&part); + bool finishRequestWithPart( + PartRequest &request, + const Media::Streaming::LoadedPart &part); + void streamMap(QString params, Webview::DataRequest request); + void sendEmbed(QByteArray hash, Webview::DataRequest request); + + void requestDone( + Webview::DataRequest request, + QByteArray bytes, + std::string mime, + int64 offset = 0, + int64 total = 0); + void requestFail(Webview::DataRequest request); + + const not_null _session; + std::shared_ptr _show; + QString _id; + std::unique_ptr _controller; + base::flat_map _files; + + QString _localBase; + base::flat_map _embeds; + base::flat_map _maps; + std::vector _resources; + int _resource = -1; + + rpl::lifetime _lifetime; + +}; + +Shown::Shown( + std::shared_ptr show, + not_null data, + bool local) +: _session(&show->session()) +, _show(show) +, _id(data->id()) { + const auto weak = base::make_weak(this); + + const auto base = local ? LookupLocalPath(show) : QString(); + data->prepare({ .saveToFolder = base }, [=](Prepared result) { + crl::on_main(weak, [=, result = std::move(result)]() mutable { + _embeds = std::move(result.embeds); + if (!base.isEmpty()) { + _localBase = base; + showLocal(std::move(result)); + } else { + showWindowed(std::move(result)); + } + }); + }); +} + +void Shown::showLocal(Prepared result) { + showProgress(0); + + QDir(_localBase).removeRecursively(); + QDir().mkpath(_localBase); + + _resources = std::move(result.resources); + writeLocal(localRoot(), result.html); +} + +void Shown::showProgress(int index) { + const auto count = int(_resources.size() + 1); + _show->showToast(u"Saving %1 / %2..."_q.arg(index + 1).arg(count)); +} + +void Shown::finishLocal(const QString &path) { + if (path.isEmpty()) { + _show->showToast(u"Failed!"_q); + } else { + _show->showToast(u"Done!"_q); + File::Launch(path); + } + _id = QString(); +} + +QString Shown::localRoot() const { + return u"page.html"_q; +} + +void Shown::writeLocal(const QString &relative, const QByteArray &data) { + const auto path = _localBase + '/' + relative; + QFileInfo(path).absoluteDir().mkpath("."); + + auto f = QFile(path); + if (!f.open(QIODevice::WriteOnly) || f.write(data) != data.size()) { + finishLocal({}); + } else { + crl::on_main(this, [=] { + loadResource(_resource + 1); + }); + } +} + +void Shown::loadResource(int index) { + _resource = index; + if (_resource == _resources.size()) { + finishLocal(_localBase + '/' + localRoot()); + return; + } + showProgress(_resource + 1); + const auto id = QString::fromUtf8(_resources[_resource]); + if (id.startsWith(u"photo/"_q)) { + loadPhoto(id, id.mid(6).toULongLong()); + } else if (id.startsWith(u"document/"_q)) { + loadDocument(id, id.mid(9).toULongLong()); + } else if (id.startsWith(u"iv/"_q)) { + loadPage(id, id.mid(3)); + } else if (id.startsWith(u"map/"_q)) { + loadMap(id, id.mid(4)); + } else if (id.startsWith(u"html/"_q)) { + writeEmbed(id, id.mid(5)); + } else { + _show->show( + Ui::MakeInformBox(u"Skipping resource %1..."_q.arg(id))); + crl::on_main(this, [=] { + loadResource(index + 1); + }); + } +} + +void Shown::loadPhoto(QString id, PhotoId photoId) { + const auto photo = _session->data().photo(photoId); + const auto media = photo->createMediaView(); + media->wanted(::Data::PhotoSize::Large, ::Data::FileOrigin()); + const auto finish = [=](QByteArray bytes) { + writeLocal(id, bytes); + }; + if (media->loaded()) { + finish(media->imageBytes(::Data::PhotoSize::Large)); + } else { + photo->session().downloaderTaskFinished( + ) | rpl::filter([=] { + return media->loaded(); + }) | rpl::take(1) | rpl::start_with_next([=] { + finish(media->imageBytes(::Data::PhotoSize::Large)); + }, _lifetime); + } +} + +void Shown::loadDocument(QString id, DocumentId documentId) { + const auto path = _localBase + '/' + id; + QFileInfo(path).absoluteDir().mkpath("."); + + const auto document = _session->data().document(documentId); + document->save(::Data::FileOrigin(), path); + if (!document->loading()) { + crl::on_main(this, [=] { + loadResource(_resource + 1); + }); + } + document->session().downloaderTaskFinished( + ) | rpl::filter([=] { + return !document->loading(); + }) | rpl::take(1) | rpl::start_with_next([=] { + crl::on_main(this, [=] { + loadResource(_resource + 1); + }); + }, _lifetime); +} + +void Shown::loadPage(QString id, QString tag) { + if (!id.endsWith(u".css"_q) && !id.endsWith(u".js"_q)) { + finishLocal({}); + return; + } + const auto pattern = u"^[a-zA-Z\\.\\-_0-9]+$"_q; + if (QRegularExpression(pattern).match(tag).hasMatch()) { + auto file = QFile(u":/iv/"_q + tag); + if (file.open(QIODevice::ReadOnly)) { + writeLocal(id, file.readAll()); + return; + } + } + finishLocal({}); +} + +void Shown::loadMap(QString id, QString params) { + using namespace ::Data; + const auto i = _maps.find(params); + if (i != end(_maps)) { + writeLocal(id, i->second.bytes); + return; + } + const auto parts = params.split(u'&'); + if (parts.size() != 3) { + finishLocal({}); + return; + } + const auto point = GeoPointFromId(parts[0].toUtf8()); + const auto size = parts[1].split(','); + const auto zoom = parts[2].toInt(); + if (size.size() != 2) { + finishLocal({}); + return; + } + const auto location = GeoPointLocation{ + .lat = point.lat, + .lon = point.lon, + .access = point.access, + .width = size[0].toInt(), + .height = size[1].toInt(), + .zoom = std::max(zoom, kGeoPointZoomMin), + .scale = kGeoPointScale, + }; + const auto prepared = ImageWithLocation{ + .location = ImageLocation( + { location }, + location.width, + location.height) + }; + auto &preview = _maps.emplace(params, MapPreview()).first->second; + preview.file = std::make_unique(); + + UpdateCloudFile( + *preview.file, + prepared, + _session->data().cache(), + kImageCacheTag, + [=](FileOrigin origin) { /* restartLoader not used here */ }); + const auto autoLoading = false; + const auto finalCheck = [=] { return true; }; + const auto done = [=](QByteArray bytes) { + const auto i = _maps.find(params); + Assert(i != end(_maps)); + i->second.bytes = std::move(bytes); + writeLocal(id, i->second.bytes); + }; + LoadCloudFile( + _session, + *preview.file, + FileOrigin(), + LoadFromCloudOrLocal, + autoLoading, + kImageCacheTag, + finalCheck, + done, + [=](bool) { done("failed..."); }); +} + +void Shown::writeEmbed(QString id, QString hash) { + const auto i = _embeds.find(hash.toUtf8()); + if (i != end(_embeds)) { + writeLocal(id, i->second); + } else { + finishLocal({}); + } +} + +void Shown::showWindowed(Prepared result) { + _controller = std::make_unique(); + _controller->dataRequests( + ) | rpl::start_with_next([=](Webview::DataRequest request) { + const auto requested = QString::fromStdString(request.id); + const auto id = QStringView(requested); + if (id.startsWith(u"photo/")) { + streamPhoto(id.mid(6).toULongLong(), std::move(request)); + } else if (id.startsWith(u"document/"_q)) { + streamFile(id.mid(9).toULongLong(), std::move(request)); + } else if (id.startsWith(u"map/"_q)) { + streamMap(id.mid(4).toUtf8(), std::move(request)); + } else if (id.startsWith(u"html/"_q)) { + sendEmbed(id.mid(5).toUtf8(), std::move(request)); + } + }, _controller->lifetime()); + const auto domain = &_session->domain(); + _controller->show(domain->local().webviewDataPath(), std::move(result)); +} + +void Shown::streamPhoto(PhotoId photoId, Webview::DataRequest request) { + using namespace Data; + + const auto photo = _session->data().photo(photoId); + if (photo->isNull()) { + requestFail(std::move(request)); + return; + } + const auto media = photo->createMediaView(); + media->wanted(PhotoSize::Large, FileOrigin()); + const auto check = [=] { + if (!media->loaded() && !media->owner()->failed(PhotoSize::Large)) { + return false; + } + requestDone( + request, + media->imageBytes(PhotoSize::Large), + "image/jpeg"); + return true; + }; + if (!check()) { + photo->session().downloaderTaskFinished( + ) | rpl::filter( + check + ) | rpl::take(1) | rpl::start(_controller->lifetime()); + } +} + +void Shown::streamFile( + DocumentId documentId, + Webview::DataRequest request) { + using namespace Data; + + const auto i = _files.find(documentId); + if (i != end(_files)) { + streamFile(i->second, std::move(request)); + return; + } + const auto document = _session->data().document(documentId); + auto loader = document->createStreamingLoader(FileOrigin(), false); + if (!loader) { + requestFail(std::move(request)); + return; + } + auto &file = _files.emplace( + documentId, + FileLoad{ + .document = document, + .loader = std::move(loader), + .mime = document->mimeString().toStdString(), + }).first->second; + + file.loader->parts( + ) | rpl::start_with_next([=](Media::Streaming::LoadedPart &&part) { + const auto i = _files.find(documentId); + Assert(i != end(_files)); + processPartInFile(i->second, std::move(part)); + }, file.lifetime); + + streamFile(file, std::move(request)); +} + +void Shown::streamFile(FileLoad &file, Webview::DataRequest request) { + constexpr auto kPart = Media::Streaming::Loader::kPartSize; + const auto size = file.document->size; + const auto last = int((size + kPart - 1) / kPart); + const auto from = int(std::min(request.offset, size) / kPart); + const auto till = (request.limit > 0) + ? std::min(request.offset + request.limit, size) + : size; + const auto parts = std::min( + int((till + kPart - 1) / kPart) - from, + kMaxLoadParts); + //auto base = IvBaseCacheKey(document); + + const auto length = std::min((from + parts) * kPart, size) + - from * kPart; + file.requests.push_back(PartRequest{ + .request = std::move(request), + .data = QByteArray(length, 0), + .loaded = std::vector(parts, false), + .offset = from * kPart, + }); + + file.loader->resetPriorities(); + const auto load = std::min(from + kKeepLoadingParts, last) - from; + for (auto i = 0; i != load; ++i) { + file.loader->load((from + i) * kPart); + } +} + +void Shown::processPartInFile( + FileLoad &file, + Media::Streaming::LoadedPart &&part) { + for (auto i = begin(file.requests); i != end(file.requests);) { + if (finishRequestWithPart(*i, part)) { + auto done = base::take(*i); + i = file.requests.erase(i); + requestDone( + std::move(done.request), + done.data, + file.mime, + done.offset, + file.document->size); + } else { + ++i; + } + } +} + +bool Shown::finishRequestWithPart( + PartRequest &request, + const Media::Streaming::LoadedPart &part) { + const auto offset = part.offset; + if (offset == Media::Streaming::LoadedPart::kFailedOffset) { + request.data = QByteArray(); + return true; + } else if (offset < request.offset + || offset >= request.offset + request.data.size()) { + return false; + } + constexpr auto kPart = Media::Streaming::Loader::kPartSize; + const auto copy = std::min( + int(part.bytes.size()), + int(request.data.size() - (offset - request.offset))); + const auto index = (offset - request.offset) / kPart; + Assert(index < request.loaded.size()); + if (request.loaded[index]) { + return false; + } + request.loaded[index] = true; + memcpy( + request.data.data() + index * kPart, + part.bytes.constData(), + copy); + return !ranges::contains(request.loaded, false); +} + +void Shown::streamMap(QString params, Webview::DataRequest request) { + using namespace ::Data; + + const auto parts = params.split(u'&'); + if (parts.size() != 3) { + finishLocal({}); + return; + } + const auto point = GeoPointFromId(parts[0].toUtf8()); + const auto size = parts[1].split(','); + const auto zoom = parts[2].toInt(); + if (size.size() != 2) { + finishLocal({}); + return; + } + const auto location = GeoPointLocation{ + .lat = point.lat, + .lon = point.lon, + .access = point.access, + .width = size[0].toInt(), + .height = size[1].toInt(), + .zoom = std::max(zoom, kGeoPointZoomMin), + .scale = kGeoPointScale, + }; + const auto prepared = ImageWithLocation{ + .location = ImageLocation( + { location }, + location.width, + location.height) + }; + auto &preview = _maps.emplace(params, MapPreview()).first->second; + preview.file = std::make_unique(); + + UpdateCloudFile( + *preview.file, + prepared, + _session->data().cache(), + kImageCacheTag, + [=](FileOrigin origin) { /* restartLoader not used here */ }); + const auto autoLoading = false; + const auto finalCheck = [=] { return true; }; + const auto done = [=](QByteArray bytes) { + const auto i = _maps.find(params); + Assert(i != end(_maps)); + i->second.bytes = std::move(bytes); + requestDone(request, i->second.bytes, "image/png"); + }; + LoadCloudFile( + _session, + *preview.file, + FileOrigin(), + LoadFromCloudOrLocal, + autoLoading, + kImageCacheTag, + finalCheck, + done, + [=](bool) { done("failed..."); }); +} + +void Shown::sendEmbed(QByteArray hash, Webview::DataRequest request) { + const auto i = _embeds.find(hash); + if (i != end(_embeds)) { + requestDone(std::move(request), i->second, "text/html"); + } else { + requestFail(std::move(request)); + } +} + +void Shown::requestDone( + Webview::DataRequest request, + QByteArray bytes, + std::string mime, + int64 offset, + int64 total) { + if (bytes.isEmpty() && mime.empty()) { + requestFail(std::move(request)); + return; + } + crl::on_main([ + done = std::move(request.done), + data = std::move(bytes), + mime = std::move(mime), + offset, + total + ] { + using namespace Webview; + done({ + .stream = std::make_unique(data, mime), + .streamOffset = offset, + .totalSize = total, + }); + }); +} + +void Shown::requestFail(Webview::DataRequest request) { + crl::on_main([done = std::move(request.done)] { + done({}); + }); +} + +bool Shown::showing( + not_null session, + not_null data) const { + return showingFrom(session) && (_id == data->id()); +} + +bool Shown::showingFrom(not_null session) const { + return (_session == session); +} + +bool Shown::activeFor(not_null session) const { + return showingFrom(session) && _controller; +} + +Instance::Instance() = default; + +Instance::~Instance() = default; + +void Instance::show( + std::shared_ptr show, + not_null data, + bool local) { + const auto session = &show->session(); + if (_shown && _shown->showing(session, data)) { + return; + } + _shown = std::make_unique(show, data, local); + if (!_tracking.contains(session)) { + _tracking.emplace(session); + session->lifetime().add([=] { + _tracking.remove(session); + if (_shown && _shown->showingFrom(session)) { + _shown = nullptr; + } + }); + } +} + +bool Instance::hasActiveWindow(not_null session) const { + return _shown && _shown->activeFor(session); +} + +void Instance::closeAll() { + _shown = nullptr; +} + +} // namespace Iv diff --git a/Telegram/SourceFiles/iv/iv_instance.h b/Telegram/SourceFiles/iv/iv_instance.h new file mode 100644 index 0000000000..7a1b21f627 --- /dev/null +++ b/Telegram/SourceFiles/iv/iv_instance.h @@ -0,0 +1,45 @@ +/* +This file is part of Telegram Desktop, +the official desktop application for the Telegram messaging service. + +For license and copyright information please follow this link: +https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL +*/ +#pragma once + +namespace Main { +class Session; +class SessionShow; +} // namespace Main + +namespace Iv { + +class Data; +class Shown; + +class Instance final { +public: + Instance(); + ~Instance(); + + void show( + std::shared_ptr show, + not_null data, + bool local); + + [[nodiscard]] bool hasActiveWindow( + not_null session) const; + + void closeAll(); + + [[nodiscard]] rpl::lifetime &lifetime(); + +private: + std::unique_ptr _shown; + base::flat_set> _tracking; + + rpl::lifetime _lifetime; + +}; + +} // namespace Iv diff --git a/Telegram/SourceFiles/iv/iv_pch.h b/Telegram/SourceFiles/iv/iv_pch.h new file mode 100644 index 0000000000..839432f44c --- /dev/null +++ b/Telegram/SourceFiles/iv/iv_pch.h @@ -0,0 +1,27 @@ +/* +This file is part of Telegram Desktop, +the official desktop application for the Telegram messaging service. + +For license and copyright information please follow this link: +https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL +*/ + +#include +#include + +#include +#include + +#include +#include +#include +#include +#include + +#include + +#include "base/flat_map.h" +#include "base/flat_set.h" + +#include "scheme.h" +#include "logs.h" diff --git a/Telegram/SourceFiles/iv/iv_prepare.cpp b/Telegram/SourceFiles/iv/iv_prepare.cpp new file mode 100644 index 0000000000..a4709502de --- /dev/null +++ b/Telegram/SourceFiles/iv/iv_prepare.cpp @@ -0,0 +1,1038 @@ +/* +This file is part of Telegram Desktop, +the official desktop application for the Telegram messaging service. + +For license and copyright information please follow this link: +https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL +*/ +#include "iv/iv_prepare.h" + +#include "base/openssl_help.h" +#include "base/unixtime.h" +#include "iv/iv_data.h" +#include "lang/lang_keys.h" +#include "ui/image/image_prepare.h" + +#include + +namespace Iv { +namespace { + +struct Attribute { + QByteArray name; + std::optional value; +}; +using Attributes = std::vector; + +struct Photo { + uint64 id = 0; + int width = 0; + int height = 0; + QByteArray minithumbnail; +}; + +struct Document { + uint64 id = 0; +}; + +class Parser final { +public: + Parser(const Source &source, const Options &options); + + [[nodiscard]] Prepared result(); + +private: + void process(const Source &source); + void process(const MTPPhoto &photo); + void process(const MTPDocument &document); + + [[nodiscard]] QByteArray prepare(QByteArray body); + + [[nodiscard]] QByteArray html( + const QByteArray &head, + const QByteArray &body); + + [[nodiscard]] QByteArray page(const MTPDpage &data); + + template + [[nodiscard]] QByteArray list(const MTPVector &data); + + [[nodiscard]] QByteArray block(const MTPDpageBlockUnsupported &data); + [[nodiscard]] QByteArray block(const MTPDpageBlockTitle &data); + [[nodiscard]] QByteArray block(const MTPDpageBlockSubtitle &data); + [[nodiscard]] QByteArray block(const MTPDpageBlockAuthorDate &data); + [[nodiscard]] QByteArray block(const MTPDpageBlockHeader &data); + [[nodiscard]] QByteArray block(const MTPDpageBlockSubheader &data); + [[nodiscard]] QByteArray block(const MTPDpageBlockParagraph &data); + [[nodiscard]] QByteArray block(const MTPDpageBlockPreformatted &data); + [[nodiscard]] QByteArray block(const MTPDpageBlockFooter &data); + [[nodiscard]] QByteArray block(const MTPDpageBlockDivider &data); + [[nodiscard]] QByteArray block(const MTPDpageBlockAnchor &data); + [[nodiscard]] QByteArray block(const MTPDpageBlockList &data); + [[nodiscard]] QByteArray block(const MTPDpageBlockBlockquote &data); + [[nodiscard]] QByteArray block(const MTPDpageBlockPullquote &data); + [[nodiscard]] QByteArray block(const MTPDpageBlockPhoto &data); + [[nodiscard]] QByteArray block(const MTPDpageBlockVideo &data); + [[nodiscard]] QByteArray block(const MTPDpageBlockCover &data); + [[nodiscard]] QByteArray block(const MTPDpageBlockEmbed &data); + [[nodiscard]] QByteArray block(const MTPDpageBlockEmbedPost &data); + [[nodiscard]] QByteArray block(const MTPDpageBlockCollage &data); + [[nodiscard]] QByteArray block(const MTPDpageBlockSlideshow &data); + [[nodiscard]] QByteArray block(const MTPDpageBlockChannel &data); + [[nodiscard]] QByteArray block(const MTPDpageBlockAudio &data); + [[nodiscard]] QByteArray block(const MTPDpageBlockKicker &data); + [[nodiscard]] QByteArray block(const MTPDpageBlockTable &data); + [[nodiscard]] QByteArray block(const MTPDpageBlockOrderedList &data); + [[nodiscard]] QByteArray block(const MTPDpageBlockDetails &data); + [[nodiscard]] QByteArray block( + const MTPDpageBlockRelatedArticles &data); + [[nodiscard]] QByteArray block(const MTPDpageBlockMap &data); + + [[nodiscard]] QByteArray block(const MTPDpageRelatedArticle &data); + + [[nodiscard]] QByteArray block(const MTPDpageTableRow &data); + [[nodiscard]] QByteArray block(const MTPDpageTableCell &data); + + [[nodiscard]] QByteArray block(const MTPDpageListItemText &data); + [[nodiscard]] QByteArray block(const MTPDpageListItemBlocks &data); + + [[nodiscard]] QByteArray block(const MTPDpageListOrderedItemText &data); + [[nodiscard]] QByteArray block( + const MTPDpageListOrderedItemBlocks &data); + + [[nodiscard]] QByteArray tag( + const QByteArray &name, + const QByteArray &body = {}); + [[nodiscard]] QByteArray tag( + const QByteArray &name, + const Attributes &attributes, + const QByteArray &body = {}); + [[nodiscard]] QByteArray utf(const MTPstring &text); + [[nodiscard]] QByteArray utf(const tl::conditional &text); + [[nodiscard]] QByteArray rich(const MTPRichText &text); + [[nodiscard]] QByteArray plain(const MTPRichText &text); + [[nodiscard]] QByteArray caption(const MTPPageCaption &caption); + + [[nodiscard]] Photo parse(const MTPPhoto &photo); + [[nodiscard]] Document parse(const MTPDocument &document); + [[nodiscard]] Geo parse(const MTPGeoPoint &geo); + + [[nodiscard]] Photo photoById(uint64 id); + [[nodiscard]] Document documentById(uint64 id); + + [[nodiscard]] QByteArray photoFullUrl(const Photo &photo); + [[nodiscard]] QByteArray documentFullUrl(const Document &document); + [[nodiscard]] QByteArray embedUrl(const QByteArray &html); + [[nodiscard]] QByteArray mapUrl( + const Geo &geo, + int width, + int height, + int zoom); + [[nodiscard]] QByteArray resource(QByteArray id); + + const Options _options; + + const QByteArray _resourcePrefix; + base::flat_set _resources; + + Prepared _result; + + bool _rtl = false; + bool _imageAsBackground = false; + bool _captionAsTitle = false; + bool _captionWrapped = false; + base::flat_map _photosById; + base::flat_map _documentsById; + + bool _hasCode = false; + bool _hasEmbeds = false; + +}; + +[[nodiscard]] bool IsVoidElement(const QByteArray &name) { + // Thanks https://developer.mozilla.org/en-US/docs/Glossary/Void_element + static const auto voids = base::flat_set{ + "area"_q, + "base"_q, + "br"_q, + "col"_q, + "embed"_q, + "hr"_q, + "img"_q, + "input"_q, + "link"_q, + "meta"_q, + "source"_q, + "track"_q, + "wbr"_q, + }; + return voids.contains(name); +} + +Parser::Parser(const Source &source, const Options &options) +: _options(options) +, _resourcePrefix(options.saveToFolder.isEmpty() + ? "http://desktop-app-resource/" + : QByteArray()) +, _rtl(source.page.data().is_rtl()) { + process(source); + _result.html = prepare(page(source.page.data())); +} + +Prepared Parser::result() { + return _result; +} + +void Parser::process(const Source &source) { + const auto &data = source.page.data(); + for (const auto &photo : data.vphotos().v) { + process(photo); + } + for (const auto &document : data.vdocuments().v) { + process(document); + } + if (source.webpagePhoto) { + process(*source.webpagePhoto); + } + if (source.webpageDocument) { + process(*source.webpageDocument); + } +} + +void Parser::process(const MTPPhoto &photo) { + _photosById.emplace( + photo.match([](const auto &data) { return data.vid().v; }), + parse(photo)); +} + +void Parser::process(const MTPDocument &document) { + _documentsById.emplace( + document.match([](const auto &data) { return data.vid().v; }), + parse(document)); +} + +template +QByteArray Parser::list(const MTPVector &data) { + auto result = QByteArrayList(); + result.reserve(data.v.size()); + for (const auto &item : data.v) { + result.append(item.match([&](const auto &data) { + return block(data); + })); + } + return result.join(QByteArray()); +} + +QByteArray Parser::block(const MTPDpageBlockUnsupported &data) { + return "Unsupported."_q; +} + +QByteArray Parser::block(const MTPDpageBlockTitle &data) { + return tag("h1", { { "class", "iv-title" } }, rich(data.vtext())); +} + +QByteArray Parser::block(const MTPDpageBlockSubtitle &data) { + return tag("h2", { { "class", "iv-subtitle" } }, rich(data.vtext())); +} + +QByteArray Parser::block(const MTPDpageBlockAuthorDate &data) { + auto inner = rich(data.vauthor()); + if (const auto date = data.vpublished_date().v) { + const auto parsed = base::unixtime::parse(date); + inner += " \xE2\x80\xA2 " + + tag("time", langDateTimeFull(parsed).toUtf8()); + } + return tag("address", inner); +} + +QByteArray Parser::block(const MTPDpageBlockHeader &data) { + return tag("h3", { { "class", "iv-header" } }, rich(data.vtext())); +} + +QByteArray Parser::block(const MTPDpageBlockSubheader &data) { + return tag("h4", { { "class", "iv-subheader" } }, rich(data.vtext())); +} + +QByteArray Parser::block(const MTPDpageBlockParagraph &data) { + return tag("p", rich(data.vtext())); +} + +QByteArray Parser::block(const MTPDpageBlockPreformatted &data) { + auto list = Attributes(); + const auto language = utf(data.vlanguage()); + if (!language.isEmpty()) { + list.push_back({ "data-language", language }); + list.push_back({ "class", "lang-" + language }); + _hasCode = true; + } + return tag("pre", list, rich(data.vtext())); +} + +QByteArray Parser::block(const MTPDpageBlockFooter &data) { + return tag("footer", { { "class", "iv-footer" } }, rich(data.vtext())); +} + +QByteArray Parser::block(const MTPDpageBlockDivider &data) { + return tag("hr", { {"class", "iv-divider" } }); +} + +QByteArray Parser::block(const MTPDpageBlockAnchor &data) { + return tag("a", { { "name", utf(data.vname())} }); +} + +QByteArray Parser::block(const MTPDpageBlockList &data) { + return tag("ul", list(data.vitems())); +} + +QByteArray Parser::block(const MTPDpageBlockBlockquote &data) { + const auto caption = rich(data.vcaption()); + const auto cite = caption.isEmpty() + ? QByteArray() + : tag("cite", caption); + return tag("blockquote", rich(data.vtext()) + cite); +} + +QByteArray Parser::block(const MTPDpageBlockPullquote &data) { + const auto caption = rich(data.vcaption()); + const auto cite = caption.isEmpty() + ? QByteArray() + : tag("cite", caption); + return tag( + "div", + { { "class", "iv-pullquote" } }, + rich(data.vtext()) + cite); +} + +QByteArray Parser::block(const MTPDpageBlockPhoto &data) { + const auto photo = photoById(data.vphoto_id().v); + if (!photo.id) { + return "Photo not found."; + } + const auto src = photoFullUrl(photo); + auto wrapStyle = QByteArray(); + if (photo.width) { + wrapStyle += "max-width:" + QByteArray::number(photo.width) + "px"; + } + const auto minithumb = Images::ExpandInlineBytes(photo.minithumbnail); + if (!minithumb.isEmpty()) { + const auto image = Images::Read({ .content = minithumb }); + wrapStyle += ";background-image:url('data:image/jpeg;base64," + + minithumb.toBase64() + + "');"; + } + const auto dimension = (photo.width && photo.height) + ? (photo.height / float64(photo.width)) + : (3 / 4.); + const auto paddingTopPercent = int(base::SafeRound(dimension * 100)); + const auto style = "background-image:url('" + src + "');" + "padding-top:" + QByteArray::number(paddingTopPercent) + "%"; + const auto inner = tag("div", { + { "class", "iv-photo" }, + { "style", style } }); + auto result = tag( + "div", + { { "class", "iv-photo-wrap" }, { "style", wrapStyle } }, + inner); + if (const auto url = data.vurl()) { + result = tag("a", { { "href", utf(*url) } }, result); + } + auto attributes = Attributes(); + if (_captionAsTitle) { + const auto caption = plain(data.vcaption().data().vtext()); + const auto credit = plain(data.vcaption().data().vtext()); + if (!caption.isEmpty() || !credit.isEmpty()) { + const auto title = (!caption.isEmpty() && !credit.isEmpty()) + ? (caption + " / " + credit) + : (caption + credit); + attributes.push_back({ "title", title }); + } + } else { + result += caption(data.vcaption()); + } + return tag("figure", attributes, result); +} + +QByteArray Parser::block(const MTPDpageBlockVideo &data) { + const auto video = documentById(data.vvideo_id().v); + if (!video.id) { + return "Video not found."; + } + const auto src = documentFullUrl(video); + auto vattributes = Attributes{}; + if (data.is_autoplay()) { + vattributes.push_back({ "preload", "auto" }); + vattributes.push_back({ "autoplay", std::nullopt }); + } else { + vattributes.push_back({ "controls", std::nullopt }); + } + if (data.is_loop()) { + vattributes.push_back({ "loop", std::nullopt }); + } + vattributes.push_back({ "muted", std::nullopt }); + auto result = tag( + "video", + vattributes, + tag("source", { { "src", src }, { "type", "video/mp4" } })); + auto attributes = Attributes(); + if (_captionAsTitle) { + const auto caption = plain(data.vcaption().data().vtext()); + const auto credit = plain(data.vcaption().data().vtext()); + if (!caption.isEmpty() || !credit.isEmpty()) { + const auto title = (!caption.isEmpty() && !credit.isEmpty()) + ? (caption + " / " + credit) + : (caption + credit); + attributes.push_back({ "title", title }); + } + } else { + result += caption(data.vcaption()); + } + return tag("figure", attributes, result); +} + +QByteArray Parser::block(const MTPDpageBlockCover &data) { + return tag("figure", data.vcover().match([&](const auto &data) { + return block(data); + })); +} + +QByteArray Parser::block(const MTPDpageBlockEmbed &data) { + _hasEmbeds = true; + auto eclass = data.is_full_width() ? QByteArray() : "nowide"; + auto width = QByteArray(); + auto height = QByteArray(); + auto iframeWidth = QByteArray(); + auto iframeHeight = QByteArray(); + const auto autosize = !data.vw(); + if (autosize) { + iframeWidth = "100%"; + eclass = "nowide"; + } else if (data.is_full_width() || !data.vw()->v) { + width = "100%"; + height = QByteArray::number(data.vh()->v) + "px"; + iframeWidth = "100%"; + iframeHeight = height; + } else { + const auto percent = data.vh()->v * 100 / data.vw()->v; + width = QByteArray::number(data.vw()->v) + "px"; + height = QByteArray::number(percent) + "%"; + } + auto attributes = Attributes(); + if (autosize) { + attributes.push_back({ "class", "autosize" }); + } + attributes.push_back({ "width", iframeWidth }); + attributes.push_back({ "height", iframeHeight }); + if (const auto url = data.vurl()) { + if (!autosize) { + attributes.push_back({ "src", utf(url) }); + } else { + attributes.push_back({ "srcdoc", utf(url) }); + } + } else if (const auto html = data.vhtml()) { + attributes.push_back({ "src", embedUrl(html->v) }); + } + if (!data.is_allow_scrolling()) { + attributes.push_back({ "scrolling", "no" }); + } + attributes.push_back({ "frameborder", "0" }); + attributes.push_back({ "allowtransparency", "true" }); + attributes.push_back({ "allowfullscreen", "true" }); + auto result = tag("iframe", attributes); + if (!autosize) { + result = tag("div", { + { "class", "iframe-wrap" }, + { "style", "width:" + width }, + }, tag("div", { + { "style", "padding-bottom: " + height }, + }, result)); + } + result += caption(data.vcaption()); + return tag("figure", { { "class", eclass } }, result); +} + +QByteArray Parser::block(const MTPDpageBlockEmbedPost &data) { + auto result = QByteArray(); + if (!data.vblocks().v.isEmpty()) { + auto address = QByteArray(); + const auto photo = photoById(data.vauthor_photo_id().v); + if (photo.id) { + const auto src = photoFullUrl(photo); + address += tag( + "figure", + { { "style", "background-image:url('" + src + "')" } }); + } + address += tag( + "a", + { { "rel", "author" }, { "onclick", "return false;" } }, + utf(data.vauthor())); + if (const auto date = data.vdate().v) { + const auto parsed = base::unixtime::parse(date); + address += tag("time", langDateTimeFull(parsed).toUtf8()); + } + const auto inner = tag("address", address) + list(data.vblocks()); + result = tag("blockquote", { { "class", "embed-post" } }, inner); + } else { + const auto url = utf(data.vurl()); + const auto inner = tag("strong", utf(data.vauthor())) + + tag("small", tag("a", { { "href", url } }, url)); + result = tag("section", { { "class", "embed-post" } }, inner); + } + result += caption(data.vcaption()); + return tag("figure", result); +} + +QByteArray Parser::block(const MTPDpageBlockCollage &data) { + auto result = tag( + "figure", + { { "class", "collage" } }, + list(data.vitems())); + return tag("figure", result + caption(data.vcaption())); +} + +QByteArray Parser::block(const MTPDpageBlockSlideshow &data) { + auto inputs = QByteArrayList(); + auto i = 0; + for (auto i = 0; i != int(data.vitems().v.size()); ++i) { + auto attributes = Attributes{ + { "type", "radio" }, + { "name", "s" }, + { "value", QByteArray::number(i) }, + { "onchange", "return IV.slideshowSlide(this);" }, + }; + if (!i) { + attributes.push_back({ "checked", std::nullopt }); + } + inputs.append(tag("label", tag("input", attributes, tag("i")))); + } + const auto form = tag( + "form", + { { "class", "slideshow-buttons" } }, + tag("fieldset", inputs.join(QByteArray()))); + auto inner = form + tag("figure", { + { "class", "slideshow" }, + { "onclick", "return IV.slideshowSlide(this, 1);" }, + }, list(data.vitems())); + auto result = tag( + "figure", + { { "class", "slideshow-wrap" } }, + inner); + return tag("figure", result + caption(data.vcaption())); +} + +QByteArray Parser::block(const MTPDpageBlockChannel &data) { + auto name = QByteArray(); + auto username = QByteArray(); + data.vchannel().match([&](const MTPDchannel &data) { + if (const auto has = data.vusername()) { + username = utf(*has); + } + name = utf(data.vtitle()); + }, [&](const MTPDchat &data) { + name = utf(data.vtitle()); + }, [](const auto &) { + }); + auto result = tag("h4", name); + if (!username.isEmpty()) { + const auto link = "https://t.me/" + username; + result = tag( + "a", + { { "href", link }, { "target", "_blank" } }, + result); + } + return tag("section", { { "class", "channel" } }, result); +} + +QByteArray Parser::block(const MTPDpageBlockAudio &data) { + const auto audio = documentById(data.vaudio_id().v); + if (!audio.id) { + return "Audio not found."; + } + const auto src = documentFullUrl(audio); + return tag("figure", tag("audio", { + { "src", src }, + { "controls", std::nullopt }, + }) + caption(data.vcaption())); +} + +QByteArray Parser::block(const MTPDpageBlockKicker &data) { + return tag("h6", { { "class", "iv-kicker" } }, rich(data.vtext())); +} + +QByteArray Parser::block(const MTPDpageBlockTable &data) { + auto classes = QByteArrayList(); + if (data.is_bordered()) { + classes.push_back("bordered"); + } + if (data.is_striped()) { + classes.push_back("striped"); + } + auto attibutes = Attributes(); + if (!classes.isEmpty()) { + attibutes.push_back({ "class", classes.join(" ") }); + } + auto title = rich(data.vtitle()); + if (!title.isEmpty()) { + title = tag("caption", title); + } + auto result = tag("table", attibutes, title + list(data.vrows())); + result = tag("figure", { { "class", "table" } }, result); + result = tag("figure", { { "class", "table-wrap" } }, result); + return tag("figure", result); +} + +QByteArray Parser::block(const MTPDpageBlockOrderedList &data) { + return tag("ol", list(data.vitems())); +} + +QByteArray Parser::block(const MTPDpageBlockDetails &data) { + auto attributes = Attributes(); + if (data.is_open()) { + attributes.push_back({ "open", std::nullopt }); + } + return tag( + "details", + attributes, + tag("summary", rich(data.vtitle())) + list(data.vblocks())); +} + +QByteArray Parser::block(const MTPDpageBlockRelatedArticles &data) { + const auto result = list(data.varticles()); + if (result.isEmpty()) { + return QByteArray(); + } + auto title = rich(data.vtitle()); + if (!title.isEmpty()) { + title = tag("h4", { { "class", "iv-related-title" } }, title); + } + return tag("section", { { "class", "iv-related" } }, title + result); +} + +QByteArray Parser::block(const MTPDpageBlockMap &data) { + const auto geo = parse(data.vgeo()); + if (!geo.access) { + return "Map not found."; + } + const auto width = 650; + const auto height = std::min(450, (data.vh().v * width / data.vw().v)); + return tag("figure", tag("img", { + { "src", mapUrl(geo, width, height, data.vzoom().v) }, + }) + caption(data.vcaption())); +} + +QByteArray Parser::block(const MTPDpageRelatedArticle &data) { + auto result = QByteArray(); + const auto photo = photoById(data.vphoto_id().value_or_empty()); + if (photo.id) { + const auto src = photoFullUrl(photo); + result += tag("i", { + { "class", "related-link-thumb" }, + { "style", "background-image:url('" + src + "')" }, + }); + } + const auto title = data.vtitle(); + const auto description = data.vdescription(); + const auto author = data.vauthor(); + const auto published = data.vpublished_date(); + if (title || description || author || published) { + auto inner = QByteArray(); + if (title) { + inner += tag( + "span", + { { "class", "related-link-title" } }, + utf(*title)); + } + if (description) { + inner += tag( + "span", + { { "class", "related-link-desc" } }, + utf(*description)); + } + if (author || published) { + const auto separator = (author && published) ? ", " : ""; + const auto parsed = base::unixtime::parse(published->v); + inner += tag( + "span", + { { "class", "related-link-source" } }, + utf(*author) + separator + langDateTimeFull(parsed).toUtf8()); + } + result += tag("span", { + { "class", "related-link-content" }, + }, inner); + } + return tag("a", { + { "class", "related-link" }, + { "href", utf(data.vurl()) }, + }, result); +} + +QByteArray Parser::block(const MTPDpageTableRow &data) { + return tag("tr", list(data.vcells())); +} + +QByteArray Parser::block(const MTPDpageTableCell &data) { + const auto text = data.vtext() ? rich(*data.vtext()) : QByteArray(); + auto style = QByteArray(); + if (data.is_align_right()) { + style += "text-align:right;"; + } else if (data.is_align_center()) { + style += "text-align:center;"; + } else { + style += "text-align:left;"; + } + if (data.is_valign_bottom()) { + style += "vertical-align:bottom;"; + } else if (data.is_valign_middle()) { + style += "vertical-align:middle;"; + } else { + style += "vertical-align:top;"; + } + auto attributes = Attributes{ { "style", style } }; + if (const auto cs = data.vcolspan()) { + attributes.push_back({ "colspan", QByteArray::number(cs->v) }); + } + if (const auto rs = data.vrowspan()) { + attributes.push_back({ "rowspan", QByteArray::number(rs->v) }); + } + return tag(data.is_header() ? "th" : "td", attributes, text); +} + +QByteArray Parser::block(const MTPDpageListItemText &data) { + return tag("li", rich(data.vtext())); +} + +QByteArray Parser::block(const MTPDpageListItemBlocks &data) { + return tag("li", list(data.vblocks())); +} + +QByteArray Parser::block(const MTPDpageListOrderedItemText &data) { + return tag("li", { { "value", utf(data.vnum()) } }, rich(data.vtext())); +} + +QByteArray Parser::block(const MTPDpageListOrderedItemBlocks &data) { + return tag( + "li", + { { "value", utf(data.vnum()) } }, + list(data.vblocks())); +} + +QByteArray Parser::utf(const MTPstring &text) { + return text.v; +} + +QByteArray Parser::utf(const tl::conditional &text) { + return text ? text->v : QByteArray(); +} + +QByteArray Parser::tag( + const QByteArray &name, + const QByteArray &body) { + return tag(name, {}, body); +} + +QByteArray Parser::tag( + const QByteArray &name, + const Attributes &attributes, + const QByteArray &body) { + auto list = QByteArrayList(); + list.reserve(attributes.size()); + for (auto &[name, value] : attributes) { + list.push_back(' ' + name + (value ? "=\"" + *value + "\"" : "")); + } + const auto serialized = list.join(QByteArray()); + return IsVoidElement(name) + ? ('<' + name + serialized + " />") + : ('<' + name + serialized + '>' + body + "'); +} + +QByteArray Parser::rich(const MTPRichText &text) { + return text.match([&](const MTPDtextEmpty &data) { + return QByteArray(); + }, [&](const MTPDtextPlain &data) { + struct Replacement { + QByteArray from; + QByteArray to; + }; + const auto replacements = std::vector{ + { "\xE2\x81\xA6", "" }, + { "\xE2\x81\xA7", "" }, + { "\xE2\x81\xA8", "" }, + { "\xE2\x81\xA9", "" }, + }; + auto text = utf(data.vtext()); + for (const auto &[from, to] : replacements) { + text.replace(from, to); + } + return text; + }, [&](const MTPDtextConcat &data) { + const auto &list = data.vtexts().v; + auto result = QByteArrayList(); + result.reserve(list.size()); + for (const auto &item : list) { + result.append(rich(item)); + } + return result.join(QByteArray()); + }, [&](const MTPDtextImage &data) { + const auto image = documentById(data.vdocument_id().v); + if (!image.id) { + return "Image not found."_q; + } + auto attributes = Attributes{ + { "class", "pic" }, + { "src", documentFullUrl(image) }, + }; + if (const auto width = data.vw().v) { + attributes.push_back({ "width", QByteArray::number(width) }); + } + if (const auto height = data.vh().v) { + attributes.push_back({ "height", QByteArray::number(height) }); + } + return tag("img", attributes); + }, [&](const MTPDtextBold &data) { + return tag("b", rich(data.vtext())); + }, [&](const MTPDtextItalic &data) { + return tag("i", rich(data.vtext())); + }, [&](const MTPDtextUnderline &data) { + return tag("u", rich(data.vtext())); + }, [&](const MTPDtextStrike &data) { + return tag("s", rich(data.vtext())); + }, [&](const MTPDtextFixed &data) { + return tag("code", rich(data.vtext())); + }, [&](const MTPDtextUrl &data) { + return tag("a", { + { "href", utf(data.vurl()) }, + }, rich(data.vtext())); + }, [&](const MTPDtextEmail &data) { + return tag("a", { + { "href", "mailto:" + utf(data.vemail()) }, + }, rich(data.vtext())); + }, [&](const MTPDtextSubscript &data) { + return tag("sub", rich(data.vtext())); + }, [&](const MTPDtextSuperscript &data) { + return tag("sup", rich(data.vtext())); + }, [&](const MTPDtextMarked &data) { + return tag("mark", rich(data.vtext())); + }, [&](const MTPDtextPhone &data) { + return tag("a", { + { "href", "tel:" + utf(data.vphone()) }, + }, rich(data.vtext())); + }, [&](const MTPDtextAnchor &data) { + const auto inner = rich(data.vtext()); + return inner.isEmpty() + ? tag("a", { { "name", utf(data.vname()) } }) + : tag( + "span", + { { "class", "reference" } }, + tag("a", { { "name", utf(data.vname()) } }) + inner); + }); +} + +QByteArray Parser::plain(const MTPRichText &text) { + return text.match([&](const MTPDtextEmpty &data) { + return QByteArray(); + }, [&](const MTPDtextPlain &data) { + return utf(data.vtext()); + }, [&](const MTPDtextConcat &data) { + const auto &list = data.vtexts().v; + auto result = QByteArrayList(); + result.reserve(list.size()); + for (const auto &item : list) { + result.append(plain(item)); + } + return result.join(QByteArray()); + }, [&](const MTPDtextImage &data) { + return QByteArray(); + }, [&](const auto &data) { + return plain(data.vtext()); + }); +} + +QByteArray Parser::caption(const MTPPageCaption &caption) { + auto text = rich(caption.data().vtext()); + const auto credit = rich(caption.data().vcredit()); + if (_captionWrapped && !text.isEmpty()) { + text = tag("span", text); + } + if (!credit.isEmpty()) { + text += tag("cite", credit); + } else if (text.isEmpty()) { + return QByteArray(); + } + return tag("figcaption", text); +} + +Photo Parser::parse(const MTPPhoto &photo) { + auto result = Photo{ + .id = photo.match([&](const auto &d) { return d.vid().v; }), + }; + auto sizes = base::flat_map(); + photo.match([](const MTPDphotoEmpty &) { + }, [&](const MTPDphoto &data) { + for (const auto &size : data.vsizes().v) { + size.match([&](const MTPDphotoSizeEmpty &data) { + }, [&](const MTPDphotoSize &data) { + sizes.emplace( + data.vtype().v, + QSize(data.vw().v, data.vh().v)); + }, [&](const MTPDphotoCachedSize &data) { + sizes.emplace( + data.vtype().v, + QSize(data.vw().v, data.vh().v)); + }, [&](const MTPDphotoStrippedSize &data) { + result.minithumbnail = data.vbytes().v; + }, [&](const MTPDphotoSizeProgressive &data) { + sizes.emplace( + data.vtype().v, + QSize(data.vw().v, data.vh().v)); + }, [&](const MTPDphotoPathSize &data) { + }); + } + }); + for (const auto attempt : { "y", "x", "w" }) { + const auto i = sizes.find(QByteArray(attempt)); + if (i != end(sizes)) { + result.width = i->second.width(); + result.height = i->second.height(); + break; + } + } + return result; +} + +Document Parser::parse(const MTPDocument &document) { + auto result = Document{ + .id = document.match([&](const auto &d) { return d.vid().v; }), + }; + document.match([](const MTPDdocumentEmpty &) { + }, [&](const MTPDdocument &data) { + }); + return result; +} + +Geo Parser::parse(const MTPGeoPoint &geo) { + return geo.match([](const MTPDgeoPointEmpty &) { + return Geo(); + }, [&](const MTPDgeoPoint &data) { + return Geo{ + .lat = data.vlat().v, + .lon = data.vlong().v, + .access = data.vaccess_hash().v, + }; + }); +} + +Photo Parser::photoById(uint64 id) { + const auto i = _photosById.find(id); + return (i != end(_photosById)) ? i->second : Photo(); +} + +Document Parser::documentById(uint64 id) { + const auto i = _documentsById.find(id); + return (i != end(_documentsById)) ? i->second : Document(); +} + +QByteArray Parser::photoFullUrl(const Photo &photo) { + return resource("photo/" + QByteArray::number(photo.id)); +} + +QByteArray Parser::documentFullUrl(const Document &document) { + return resource("document/" + QByteArray::number(document.id)); +} + +QByteArray Parser::embedUrl(const QByteArray &html) { + auto binary = std::array{}; + SHA256( + reinterpret_cast(html.data()), + html.size(), + binary.data()); + const auto hex = [](uchar value) -> char { + return (value >= 10) ? ('a' + (value - 10)) : ('0' + value); + }; + auto result = QByteArray(); + result.reserve(binary.size() * 2); + auto index = 0; + for (const auto byte : binary) { + result.push_back(hex(byte / 16)); + result.push_back(hex(byte % 16)); + } + result += ".html"; + _result.embeds.emplace(result, html); + return resource("html/" + result); +} + +QByteArray Parser::mapUrl(const Geo &geo, int width, int height, int zoom) { + return resource("map/" + + GeoPointId(geo) + "&" + + QByteArray::number(width) + "," + + QByteArray::number(height) + "&" + + QByteArray::number(zoom)); +} + +QByteArray Parser::resource(QByteArray id) { + if (!_options.saveToFolder.isEmpty() && _resources.emplace(id).second) { + _result.resources.push_back(id); + } + return _resourcePrefix + id; +} + +QByteArray Parser::page(const MTPDpage &data) { + const auto html = list(data.vblocks()); + if (html.isEmpty()) { + return html; + } + auto attributes = Attributes(); + if (_rtl) { + attributes.push_back({ "dir", "rtl" }); + attributes.push_back({ "class", "rtl" }); + } + return tag("article", attributes, html); +} + +QByteArray Parser::prepare(QByteArray body) { + auto head = QByteArray(); + auto js = QByteArray(); + if (body.isEmpty()) { + body = tag( + "section", + { { "class", "message" } }, + tag("aside", "Failed." + tag("cite", "Failed."))); + } + if (_hasCode) { + head += R"( + + +)"_q; + js += "IV.initPreBlocks();"; + } + if (_hasEmbeds) { + js += "IV.initEmbedBlocks();"; + } + if (!js.isEmpty()) { + body += tag("script", js); + } + return html(head, body); +} + +QByteArray Parser::html(const QByteArray &head, const QByteArray &body) { + return R"( + + + + + + + + )"_q + head + R"( + + )"_q + body + R"( + +)"_q; +} + +} // namespace + +Prepared Prepare(const Source &source, const Options &options) { + auto parser = Parser(source, options); + return parser.result(); +} + +} // namespace Iv diff --git a/Telegram/SourceFiles/iv/iv_prepare.h b/Telegram/SourceFiles/iv/iv_prepare.h new file mode 100644 index 0000000000..f5971d6073 --- /dev/null +++ b/Telegram/SourceFiles/iv/iv_prepare.h @@ -0,0 +1,25 @@ +/* +This file is part of Telegram Desktop, +the official desktop application for the Telegram messaging service. + +For license and copyright information please follow this link: +https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL +*/ +#pragma once + +namespace Iv { + +struct Options; +struct Prepared; + +struct Source { + MTPPage page; + std::optional webpagePhoto; + std::optional webpageDocument; +}; + +[[nodiscard]] Prepared Prepare( + const Source &source, + const Options &options); + +} // namespace Iv diff --git a/Telegram/cmake/td_iv.cmake b/Telegram/cmake/td_iv.cmake new file mode 100644 index 0000000000..64fe487cef --- /dev/null +++ b/Telegram/cmake/td_iv.cmake @@ -0,0 +1,35 @@ +# This file is part of Telegram Desktop, +# the official desktop application for the Telegram messaging service. +# +# For license and copyright information please follow this link: +# https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL + +add_library(td_iv OBJECT) +init_non_host_target(td_iv) +add_library(tdesktop::td_iv ALIAS td_iv) + +target_precompile_headers(td_iv PRIVATE ${src_loc}/iv/iv_pch.h) +nice_target_sources(td_iv ${src_loc} +PRIVATE + iv/iv_controller.cpp + iv/iv_controller.h + iv/iv_data.cpp + iv/iv_data.h + iv/iv_pch.h + iv/iv_prepare.cpp + iv/iv_prepare.h +) + +target_include_directories(td_iv +PUBLIC + ${src_loc} +) + +target_link_libraries(td_iv +PUBLIC + desktop-app::lib_ui + tdesktop::td_scheme +PRIVATE + desktop-app::lib_webview + tdesktop::td_lang +)