Automatically generate new wallpaper

Retired – Please see new Community Topic

This topic is old. Please see the new topic here:
–> New and Improved Wallpaper Generator <–


Original post

Desktop%20Wanikani%20Screenshot

Hello, fellow acolytes!

This is based off of the awesome Wallpaper Generator by @akranis. This allows you to update your WaniKani progress wallpaper by simply right-clicking on your desktop, and choosing “Refresh WaniKani Wallpaper” as shown in the picture above. This also acts as a PHP port of the wallpaper generator. These instructions are written for Windows 10, but it might also work with earlier versions of Windows and other operating systems with some work.

1) Install PHP

Please see my Step 1 from my other post here:
https://community.wanikani.com/t/automatically-open-wanikani-when-its-review-time/34192

2) Create a folder for the code file

Create a folder somewhere on your computer for putting the code file in. This folder will eventually hold three things: 1) the code file, 2) a small wallpaper changer program, and 3) the wallpaper itself. I recommend putting it in your user folder, which is located at C:\Users(your username), but placing it on your desktop or in your root directory will work, too. For my example, I created the folder at C:\Users\Ben\WaniKani Wallpaper\.

3) Download WallpaperChanger

WallpaperChanger is a small program by Phil Hansen. Go to the following link, and download the latest version of WallpaperChanger.exe, and save it to the folder you created in step 2.

https://github.com/philhansen/WallpaperChanger/releases/

4) Create the code file

Open up Notepad or your favorite code editor. Copy and paste the code section below, and modify the API key and settings as necessary. Your API key is found at https://www.wanikani.com/api.

Because there are Kanji characters in the code file, make sure to save the code file with UTF-8 encoding (see picture). If UTF-8 doesn’t work, try Unicode.

utf-8

The code:

<?php

// Settings
$settings = [
    "api_key" => 'YOUR_API_KEY',
    "width" => 1920,
    "height" => 1080,
    "margin" => [
        "top" => 10,
        "right" => 10,
        "bottom" => 50,
        "left" => 10,
    ],
    "colors" => [
        // Colors can be in hex string format or decimal array format
        // Hex String example: '#294DDB'
        // Decimal Array example: [41, 77, 219]
        "background"    => '#000000',
        "unseen"        => '#303030',
        "apprentice"    => '#DD0093',
        "guru"          => '#882D9E',
        "master"        => '#294DDB',
        "enlighten"     => '#0093DD',
        "burned"        => '#FFFFFF',
    ],
    "a_colors" => [], // allocated colors -- populated later in the code below
    "fontAdjustment" => 0.72,
    "debug" => false, // set to true to draw a magenta outline where the characters are supposed to draw
    "fontfile" => "/Windows/Fonts/meiryo.ttc",
];

// Set the Kanji order
$all_kanji = str_replace(PHP_EOL, "", "
一二三四五六七八九十口日月田目古吾冒朋明唱晶品呂昌早旭世胃旦胆亘
凹凸旧自白百中千舌升昇丸寸専博占上下卓朝只貝貞員見児元頁頑凡負万
句肌旬勺的首乙乱直具真工左右有賄貢項刀刃切召昭則副別丁町可頂子孔
了女好如母貫兄克小少大多夕汐外名石肖硝砕砂削光太器臭妙省厚奇川州
順水氷永泉原願泳沼沖江汁潮源活消況河泊湖測土吐圧埼垣圭封涯寺時均
火炎煩淡灯畑災灰点照魚漁里黒墨鯉量厘埋同洞胴向尚字守完宣宵安宴寄
富貯木林森桂柏枠梢棚杏桐植枯朴村相机本札暦案燥未末沫味妹朱株若草
苦寛薄葉模漠墓暮膜苗兆桃眺犬状黙然荻狩猫牛特告先洗介界茶合塔王玉
宝珠現狂皇呈全栓理主注柱金銑鉢銅釣針銘鎮道導辻迅造迫逃辺巡車連軌
輸前各格略客額夏処条落冗軍輝運冠夢坑高享塾熟亭京涼景鯨舎周週士吉
壮荘売学覚栄書津牧攻敗枚故敬言警計獄訂討訓詔詰話詠詩語読調談諾諭
式試弐域賊栽載茂成城誠威滅減桟銭浅止歩渉頻肯企歴武賦正証政定錠走
超赴越是題堤建延誕礎婿衣裁装裏壊哀遠猿初布帆幅帽幕幌錦市姉肺帯滞
刺制製転芸雨雲曇雷霜冬天橋嬌立泣章競帝童瞳鐘商嫡適滴敵匕北背比昆
皆混渇謁褐喝旨脂壱毎敏梅海乞乾腹複欠吹炊歌軟次茨資姿諮賠培剖音暗
韻識鏡境亡盲妄荒望方妨坊芳肪訪放激脱説鋭曽増贈東棟凍妊廷染燃賓歳
県栃地池虫蛍蛇虹蝶独蚕風己起妃改記包胞砲泡亀電竜滝豚逐遂家嫁豪腸
場湯羊美洋詳鮮達羨差着唯焦礁集准進雑雌準奮奪確午許歓権観羽習翌曜
濯曰困固国団因姻園回壇店庫庭庁床麻磨心忘忍認忌志誌忠串患思恩応意
想息憩恵恐惑感憂寡忙悦恒悼悟怖慌悔憎慣愉惰慎憾憶慕添必泌手看摩我
義議犠抹抱搭抄抗批招拓拍打拘捨拐摘挑指持括揮推揚提損拾担拠描操接
掲掛研戒械鼻刑型才財材存在乃携及吸扱丈史吏更硬又双桑隻護獲奴怒友
抜投没設撃殻支技枝肢茎怪軽叔督寂淑反坂板返販爪妥乳浮将奨採菜受授
愛払広拡鉱弁雄台怠治始胎窓去法会至室到致互棄育撤充銃硫流允唆出山
拙岩炭岐峠崩密蜜嵐崎入込分貧頒公松翁訟谷浴容溶欲裕鉛沿賞党堂常裳
掌皮波婆披破被残殉殊殖列裂烈死葬瞬耳取趣最撮恥職聖敢聴懐慢漫買置
罰寧濁環還夫扶渓規替賛潜失鉄迭臣姫蔵臓賢堅臨覧巨拒力男労募劣功勧
努励加賀架脇脅協行律復得従徒待往征径彼役徳徹徴懲微街衡稿稼程税稚
和移秒秋愁私秩秘称利梨穫穂稲香季委秀透誘穀菌米粉粘粒粧迷粋糧菊奥
数楼類漆様求球救竹笑笠笹筋箱筆筒等算答策簿築人佐但住位仲体悠件仕
他伏伝仏休仮伯俗信佳依例個健側侍停値倣倒偵僧億儀償仙催仁侮使便倍
優伐宿傷保褒傑付符府任賃代袋貸化花貨傾何荷俊傍久畝囚内丙柄肉腐座
卒傘匁以似併瓦瓶宮営善年夜液塚幣弊喚換融施旋遊旅勿物易賜尿尼尻泥
塀履屋握屈掘堀居据層局遅漏刷尺尽沢訳択昼戸肩房扇炉戻涙雇顧啓示礼
祥祝福祉社視奈尉慰款禁襟宗崇祭察擦由抽油袖宙届笛軸甲押岬挿申伸神
捜果菓課裸斤析所祈近折哲逝誓暫漸断質斥訴昨詐作雪録尋急穏侵浸寝婦
掃当争浄事唐糖康逮伊君群耐需儒端両満画歯曲曹遭漕槽斗料科図用庸備
昔錯借惜措散廿庶遮席度渡奔噴墳憤焼暁半伴畔判券巻圏勝藤謄片版之乏
芝不否杯矢矯族知智矛柔務霧班帰弓引弔弘強弱沸費第弟巧号朽誇汚与写
身射謝老考孝教拷者煮著署暑諸猪渚賭峡狭挟追師帥官棺管父交効較校足
促距路露跳躍践踏骨滑髄禍渦過阪阿際障随陪陽陳防附院陣隊墜降階陛隣
隔隠堕陥穴空控突究窒窃窪搾窯窮探深丘岳兵浜糸織繕縮繁縦線締維羅練
緒続絵統絞給絡結終級紀紅納紡紛紹経紳約細累索総綿絹繰継緑縁網緊紫
縛縄幼後幽幾機玄畜蓄弦擁滋慈磁系係孫懸却脚卸御服命令零齢冷領鈴勇
通踊疑擬凝範犯厄危宛腕苑怨柳卵留貿印興酉酒酌酵酷酬酪酢酔配酸猶尊
豆頭短豊鼓喜樹皿血盆盟盗温監濫鑑猛盛塩銀恨根即爵節退限眼良朗浪娘
食飯飲飢餓飾館養飽既概慨平呼坪評刈希凶胸離殺純鈍辛辞梓宰壁避新薪
親幸執報叫糾収卑碑陸睦勢熱菱陵亥核刻該劾述術寒醸譲壌嬢毒素麦青精
請情晴清静責績積債漬表俵潔契喫害轄割憲生星姓性牲産隆峰縫拝寿鋳籍
春椿泰奏実奉俸棒謹勤漢嘆難華垂睡錘乗剰今含吟念琴陰予序預野兼嫌鎌
謙廉西価要腰票漂標栗遷覆煙南楠献門問閲閥間簡開閉閣閑聞潤欄闘倉創
非俳排悲罪輩扉侯候決快偉違緯衛韓干肝刊汗軒岸幹芋宇余除徐叙途斜塗
束頼瀬勅疎速整剣険検倹重動勲働種衝薫病痴痘症疾痢疲疫痛癖匿匠医匹
区枢殴欧抑仰迎登澄発廃僚寮療彫形影杉彩彰彦顔須膨参惨修珍診文対紋
蚊斉剤済斎粛塁楽薬率渋摂央英映赤赦変跡蛮恋湾黄横把色絶艶肥甘紺某
謀媒欺棋旗期碁基甚勘堪貴遺遣舞無組粗租祖阻査助宜畳並普譜湿顕繊霊
業撲僕共供異翼洪港暴爆恭選殿井囲耕亜悪円角触解再講購構溝論倫輪偏
遍編冊典氏紙婚低抵底民眠捕浦蒲舗補邸郭郡郊部都郵邦郷響郎廊盾循派
脈衆逓段鍛后幻司伺詞飼嗣舟舶航般盤搬船艦艇瓜弧孤繭益暇敷来気汽飛
沈妻衰衷面革靴覇声呉娯誤蒸承函極牙芽邪雅釈番審翻藩毛耗尾宅託為偽
長張帳脹髪展喪巣単戦禅弾桜獣脳悩厳鎖挙誉猟鳥鳴鶴烏蔦鳩鶏島暖媛援
緩属嘱偶遇愚隅逆塑岡鋼綱剛缶陶揺謡就懇墾免逸晩勉象像馬駒験騎駐駆
駅騒駄驚篤騰虎虜膚虚戯虞慮劇虐鹿薦慶麗熊能態寅演辰辱震振娠唇農濃
送関咲鬼醜魂魔魅塊襲嚇朕雰箇錬遵罷屯且藻隷癒丹潟丑卯巳謎椅翔贅芯
酎俺闇枕綺鍋醤丼賂伎斐墟蜂拳遜狙噌誰呪也頃叱斬鍵巾爽阜庄瞭崖箸淀
堰鰐隙貼蟹鬱々
");
$num_kanji = mb_strlen($all_kanji);

// Set the working directory to the folder this code file is in
chdir(dirname(__FILE__));

// Shortcut variables for some of the settings
$w = $settings["width"];
$h = $settings["height"];
// Follows CSS margin order, i.e. top, right, bottom, left
$m0 = $settings["margin"]["top"];
$m1 = $settings["margin"]["right"];
$m2 = $settings["margin"]["bottom"];
$m3 = $settings["margin"]["left"];

// Make a character-associative Progress Report array from an API Call
$api_call = json_decode(file_get_contents('https://www.wanikani.com/api/user/'.$settings["api_key"].'/kanji'), true);
$progress_report = [];
foreach ($api_call["requested_information"] as $character_report) {
    $progress_report[$character_report["character"]] = $character_report;
}

// Create Canvas
$canvas = imagecreatetruecolor($w, $h);

// Allocate colors
foreach ($settings["colors"] as $color_name=>$color) {
    if (gettype($color) == "string") $color = hex_to_array($color);
    $settings["a_colors"][$color_name] = imagecolorallocate($canvas, $color[0], $color[1], $color[2]);
}

// Fill the background
imagefill($canvas, 0, 0, $settings["a_colors"]["background"]);

// Draw a magenta outline for debug purposes
if ($settings["debug"])
imagerectangle($canvas, $m3, $m0,$w-$m1,$h-$m2,
    imagecolorallocate($canvas, 255, 0, 255));

// Figure out the fit
$drawWidth = $w - $m3 - $m1;
$drawHeight = $h - $m0 - $m2;
$aspectRatio = $drawWidth / $drawHeight;
$bestFit = findBestFit($drawWidth, $drawHeight, $num_kanji);

// Find the y-offset, needed to perfectly align the text.
$y_offset = floor($bestFit["fontSize"]) * 1.2;

// Draw each character
for ($i = 0; $i < $num_kanji; $i++) {
    $character = mb_substr($all_kanji, $i, 1);
    $color = getColor($character);

    $y = $m0 + floor($i / $bestFit["w"]) * $bestFit["charHeight"];
    $x = $m3 + ($i % $bestFit["w"]) * $bestFit["charWidth"];

    // Draw the character
    imagettftext($canvas, $bestFit["fontSize"], 0, $x, $y + $y_offset, $color, $settings["fontfile"], $character);
}

// Output and free from memory
imagepng($canvas, "wallpaper.png");
system("WallpaperChanger.exe wallpaper.png");
imagedestroy($canvas);

print "\nFinished!\n";

// Helper Functions
function hex_to_array($hex) {
    $array = [];

    // Keep only alphanumeric characters
    $hex = preg_replace("/[^a-zA-Z0-9]+/", "", $hex);

    // Grab each two characters, and add to the array
    for ($i = 0; $i < 3; $i++) {
        $array[] = intval(base_convert(substr($hex, $i*2, 2), "16", "10"));
    }

    return $array;
}

function getColor($character) {
    global $progress_report, $settings;
    if (!isset($progress_report[$character])) {
        return $settings["a_colors"]["unseen"];
    }

    if (!isset($progress_report[$character]["user_specific"]) || !is_array($progress_report[$character]["user_specific"])) {
        return $settings["a_colors"]["unseen"];
    }

    return $settings["a_colors"][$progress_report[$character]["user_specific"]["srs"]];
}

function findBestFit($w, $h, $elementsToFit) {

    global $settings;
    $sqrt = ceil(sqrt($elementsToFit)) + 1;

    $aspectRatio = $w / $h;

    $y = ceil($sqrt / ((1 + $aspectRatio)/2));
    $x = ceil($elementsToFit / $y);

    $charWidth = $w / $x;
    $charHeight = $h / $y;
    $fontSize = min($charWidth, $charHeight);
    $totalArea = $w * $h;
    $coveredArea = $elementsToFit * pow($fontSize, 2);
    $fit = $coveredArea / $totalArea;

    return [
        "fit" => $fit,
        "w" => $x,
        "h" => $y,
        "fontSize" => $fontSize * $settings["fontAdjustment"],
        "charWidth" => $charWidth,
        "charHeight" => $charHeight,
    ];
}

I named my code file Update Wallpaper.txt, so that the code file is located at C:\Users\Ben\WaniKani Wallpaper\Update Wallpaper.txt.

To test that it works, open up a command prompt and run the script from php. This is the command to run it on my computer:

C:\php\php.exe -dextension=openssl -dextension=gd2 -dextension=mbstring "C:\Users\Ben\WaniKani Wallpaper\Update Wallpaper.txt"

If everything works good so far, then you should get a “Finished!” message like in the next picture, and also your wallpaper should update to your latest WaniKani progress.

5) Add the Desktop Context Menu Item by Modifying the Registry

Please proceed very cautiously and at your own risk. Editing the computer registry is serious business, and deleting and/or modifying items you shouldn’t can result in system crashes, data corruption, and more. I am not responsible for any losses caused by your mistakes here in this step.

Open up Registry Editor. Do Windows+R (hold down the Windows key on the keyboard and tap the R key once), and type “regedit” and hit OK.

image

In the left panel, open up HKEY_CLASSES_ROOT, scroll down until you see DesktopBackground and open it, and then open Shell, and create a new key under it by right-clicking on Shell and choosing New->Key.

image

Name the new Key as “Refresh WaniKani Wallpaper” or something similar, and right-click the new Key and create another Key underneath it exactly called command. After that, select the new command Key that you just created.

image

Now, in the right panel, double-click on “(Default)”, and type in the command that you tested out earlier in Command Prompt. For example, the command for my set-up is C:\php\php.exe -dextension=openssl -dextension=gd2 -dextension=mbstring "C:\Users\Ben\WaniKani Wallpaper\Update Wallpaper.txt"

image

6) Go burn some turtles

That’s it! To test that it all works, right-click on your desktop wallpaper, and you should have a new item labeled “Refresh WaniKani Wallpaper”.

Thank you for checking this out. If it helps, let me know :slight_smile:

12 Likes

Nice!!

What about for Mac??

1 Like

Hi @emucat!

Would you test these new instructions for me please? I don’t have a Mac so I can’t test it myself.

1) Install PHP on Mac

Open a Terminal, and run the following command which is borrowed from https://php-osx.liip.ch/
curl -s https://php-osx.liip.ch/install.sh | bash -s 7.2

2) Create a folder for the code file and font

See this link for how to create a folder: https://support.apple.com/kb/PH25633

3) Download a Japanese Font

Download this font: https://fonts.google.com/specimen/Kosugi+Maru. To download a font from Google Fonts, click on the “(+) SELECT THIS FONT” link in the upper right, and then click on the “1 Family Selected” bar at the bottom of the screen, and then click on the download link.

image

For more font options, you can go to https://www.freejapanesefont.com/, but you will need to modify the code file to match the new font filename.

Extract the font you downloaded to the folder you created in step 2

4) Create the code file

Open TextEdit from your Applications folder. To get to the Application folder, click on your desktop, then click Go on the menu bar, and choose Applications.

With TextEdit open, from the menu bar, click TextEdit->Preferences. In the New Document tab, make sure that the Format is set to “Plain text”. In the Open and Save tab, make sure that the Encoding is set to “Unicode (UTF-8)”.

Copy and paste and save the code as in my earlier instructions, except using this code below, and also name this file so that it ends with “.command”, for example WaniKani Wallpaper.command. Save it to the folder created in step 2.

#!/usr/bin/php
<?php

// Settings
$settings = [
    "api_key" => 'YOUR_API_KEY',
    "width" => 1920,
    "height" => 1080,
    "margin" => [
        "top" => 10,
        "right" => 10,
        "bottom" => 50,
        "left" => 10,
    ],
    "colors" => [
        // Colors can be in hex string format or decimal array format
        // Hex String example: '#294DDB'
        // Decimal Array example: [41, 77, 219]
        "background"    => '#000000',
        "unseen"        => '#303030',
        "apprentice"    => '#DD0093',
        "guru"          => '#882D9E',
        "master"        => '#294DDB',
        "enlighten"     => '#0093DD',
        "burned"        => '#FFFFFF',
    ],
    "a_colors" => [], // allocated colors -- populated later in the code below
    "fontAdjustment" => 0.72,
    "debug" => false, // set to true to draw a magenta outline where the characters are supposed to draw
    "fontfile" => realpath("KosugiMaru-Regular.ttf"),
];

// Make sure we can find the font file
if (!file_exists($settings["fontfile"])) {
    $settings["fontfile"] = "~".$settings["fontfile"];
    if (!file_exists($settings["fontfile"])) {
        print "Cannot find the font file at ".$settings["fontfile"];
        sleep(10);
        exit;
    }
}

// Set the Kanji order
$all_kanji = str_replace(PHP_EOL, "", "
一二三四五六七八九十口日月田目古吾冒朋明唱晶品呂昌早旭世胃旦胆亘
凹凸旧自白百中千舌升昇丸寸専博占上下卓朝只貝貞員見児元頁頑凡負万
句肌旬勺的首乙乱直具真工左右有賄貢項刀刃切召昭則副別丁町可頂子孔
了女好如母貫兄克小少大多夕汐外名石肖硝砕砂削光太器臭妙省厚奇川州
順水氷永泉原願泳沼沖江汁潮源活消況河泊湖測土吐圧埼垣圭封涯寺時均
火炎煩淡灯畑災灰点照魚漁里黒墨鯉量厘埋同洞胴向尚字守完宣宵安宴寄
富貯木林森桂柏枠梢棚杏桐植枯朴村相机本札暦案燥未末沫味妹朱株若草
苦寛薄葉模漠墓暮膜苗兆桃眺犬状黙然荻狩猫牛特告先洗介界茶合塔王玉
宝珠現狂皇呈全栓理主注柱金銑鉢銅釣針銘鎮道導辻迅造迫逃辺巡車連軌
輸前各格略客額夏処条落冗軍輝運冠夢坑高享塾熟亭京涼景鯨舎周週士吉
壮荘売学覚栄書津牧攻敗枚故敬言警計獄訂討訓詔詰話詠詩語読調談諾諭
式試弐域賊栽載茂成城誠威滅減桟銭浅止歩渉頻肯企歴武賦正証政定錠走
超赴越是題堤建延誕礎婿衣裁装裏壊哀遠猿初布帆幅帽幕幌錦市姉肺帯滞
刺制製転芸雨雲曇雷霜冬天橋嬌立泣章競帝童瞳鐘商嫡適滴敵匕北背比昆
皆混渇謁褐喝旨脂壱毎敏梅海乞乾腹複欠吹炊歌軟次茨資姿諮賠培剖音暗
韻識鏡境亡盲妄荒望方妨坊芳肪訪放激脱説鋭曽増贈東棟凍妊廷染燃賓歳
県栃地池虫蛍蛇虹蝶独蚕風己起妃改記包胞砲泡亀電竜滝豚逐遂家嫁豪腸
場湯羊美洋詳鮮達羨差着唯焦礁集准進雑雌準奮奪確午許歓権観羽習翌曜
濯曰困固国団因姻園回壇店庫庭庁床麻磨心忘忍認忌志誌忠串患思恩応意
想息憩恵恐惑感憂寡忙悦恒悼悟怖慌悔憎慣愉惰慎憾憶慕添必泌手看摩我
義議犠抹抱搭抄抗批招拓拍打拘捨拐摘挑指持括揮推揚提損拾担拠描操接
掲掛研戒械鼻刑型才財材存在乃携及吸扱丈史吏更硬又双桑隻護獲奴怒友
抜投没設撃殻支技枝肢茎怪軽叔督寂淑反坂板返販爪妥乳浮将奨採菜受授
愛払広拡鉱弁雄台怠治始胎窓去法会至室到致互棄育撤充銃硫流允唆出山
拙岩炭岐峠崩密蜜嵐崎入込分貧頒公松翁訟谷浴容溶欲裕鉛沿賞党堂常裳
掌皮波婆披破被残殉殊殖列裂烈死葬瞬耳取趣最撮恥職聖敢聴懐慢漫買置
罰寧濁環還夫扶渓規替賛潜失鉄迭臣姫蔵臓賢堅臨覧巨拒力男労募劣功勧
努励加賀架脇脅協行律復得従徒待往征径彼役徳徹徴懲微街衡稿稼程税稚
和移秒秋愁私秩秘称利梨穫穂稲香季委秀透誘穀菌米粉粘粒粧迷粋糧菊奥
数楼類漆様求球救竹笑笠笹筋箱筆筒等算答策簿築人佐但住位仲体悠件仕
他伏伝仏休仮伯俗信佳依例個健側侍停値倣倒偵僧億儀償仙催仁侮使便倍
優伐宿傷保褒傑付符府任賃代袋貸化花貨傾何荷俊傍久畝囚内丙柄肉腐座
卒傘匁以似併瓦瓶宮営善年夜液塚幣弊喚換融施旋遊旅勿物易賜尿尼尻泥
塀履屋握屈掘堀居据層局遅漏刷尺尽沢訳択昼戸肩房扇炉戻涙雇顧啓示礼
祥祝福祉社視奈尉慰款禁襟宗崇祭察擦由抽油袖宙届笛軸甲押岬挿申伸神
捜果菓課裸斤析所祈近折哲逝誓暫漸断質斥訴昨詐作雪録尋急穏侵浸寝婦
掃当争浄事唐糖康逮伊君群耐需儒端両満画歯曲曹遭漕槽斗料科図用庸備
昔錯借惜措散廿庶遮席度渡奔噴墳憤焼暁半伴畔判券巻圏勝藤謄片版之乏
芝不否杯矢矯族知智矛柔務霧班帰弓引弔弘強弱沸費第弟巧号朽誇汚与写
身射謝老考孝教拷者煮著署暑諸猪渚賭峡狭挟追師帥官棺管父交効較校足
促距路露跳躍践踏骨滑髄禍渦過阪阿際障随陪陽陳防附院陣隊墜降階陛隣
隔隠堕陥穴空控突究窒窃窪搾窯窮探深丘岳兵浜糸織繕縮繁縦線締維羅練
緒続絵統絞給絡結終級紀紅納紡紛紹経紳約細累索総綿絹繰継緑縁網緊紫
縛縄幼後幽幾機玄畜蓄弦擁滋慈磁系係孫懸却脚卸御服命令零齢冷領鈴勇
通踊疑擬凝範犯厄危宛腕苑怨柳卵留貿印興酉酒酌酵酷酬酪酢酔配酸猶尊
豆頭短豊鼓喜樹皿血盆盟盗温監濫鑑猛盛塩銀恨根即爵節退限眼良朗浪娘
食飯飲飢餓飾館養飽既概慨平呼坪評刈希凶胸離殺純鈍辛辞梓宰壁避新薪
親幸執報叫糾収卑碑陸睦勢熱菱陵亥核刻該劾述術寒醸譲壌嬢毒素麦青精
請情晴清静責績積債漬表俵潔契喫害轄割憲生星姓性牲産隆峰縫拝寿鋳籍
春椿泰奏実奉俸棒謹勤漢嘆難華垂睡錘乗剰今含吟念琴陰予序預野兼嫌鎌
謙廉西価要腰票漂標栗遷覆煙南楠献門問閲閥間簡開閉閣閑聞潤欄闘倉創
非俳排悲罪輩扉侯候決快偉違緯衛韓干肝刊汗軒岸幹芋宇余除徐叙途斜塗
束頼瀬勅疎速整剣険検倹重動勲働種衝薫病痴痘症疾痢疲疫痛癖匿匠医匹
区枢殴欧抑仰迎登澄発廃僚寮療彫形影杉彩彰彦顔須膨参惨修珍診文対紋
蚊斉剤済斎粛塁楽薬率渋摂央英映赤赦変跡蛮恋湾黄横把色絶艶肥甘紺某
謀媒欺棋旗期碁基甚勘堪貴遺遣舞無組粗租祖阻査助宜畳並普譜湿顕繊霊
業撲僕共供異翼洪港暴爆恭選殿井囲耕亜悪円角触解再講購構溝論倫輪偏
遍編冊典氏紙婚低抵底民眠捕浦蒲舗補邸郭郡郊部都郵邦郷響郎廊盾循派
脈衆逓段鍛后幻司伺詞飼嗣舟舶航般盤搬船艦艇瓜弧孤繭益暇敷来気汽飛
沈妻衰衷面革靴覇声呉娯誤蒸承函極牙芽邪雅釈番審翻藩毛耗尾宅託為偽
長張帳脹髪展喪巣単戦禅弾桜獣脳悩厳鎖挙誉猟鳥鳴鶴烏蔦鳩鶏島暖媛援
緩属嘱偶遇愚隅逆塑岡鋼綱剛缶陶揺謡就懇墾免逸晩勉象像馬駒験騎駐駆
駅騒駄驚篤騰虎虜膚虚戯虞慮劇虐鹿薦慶麗熊能態寅演辰辱震振娠唇農濃
送関咲鬼醜魂魔魅塊襲嚇朕雰箇錬遵罷屯且藻隷癒丹潟丑卯巳謎椅翔贅芯
酎俺闇枕綺鍋醤丼賂伎斐墟蜂拳遜狙噌誰呪也頃叱斬鍵巾爽阜庄瞭崖箸淀
堰鰐隙貼蟹鬱々
");
$num_kanji = mb_strlen($all_kanji);

// Set the working directory to the folder this code file is in
chdir(dirname(__FILE__));

// Shortcut variables for some of the settings
$w = $settings["width"];
$h = $settings["height"];
// Follows CSS margin order, i.e. top, right, bottom, left
$m0 = $settings["margin"]["top"];
$m1 = $settings["margin"]["right"];
$m2 = $settings["margin"]["bottom"];
$m3 = $settings["margin"]["left"];

// Make a character-associative Progress Report array from an API Call
$api_call = json_decode(file_get_contents('https://www.wanikani.com/api/user/'.$settings["api_key"].'/kanji'), true);
$progress_report = [];
foreach ($api_call["requested_information"] as $character_report) {
    $progress_report[$character_report["character"]] = $character_report;
}

// Create Canvas
$canvas = imagecreatetruecolor($w, $h);

// Allocate colors
foreach ($settings["colors"] as $color_name=>$color) {
    if (gettype($color) == "string") $color = hex_to_array($color);
    $settings["a_colors"][$color_name] = imagecolorallocate($canvas, $color[0], $color[1], $color[2]);
}

// Fill the background
imagefill($canvas, 0, 0, $settings["a_colors"]["background"]);

// Draw a magenta outline for debug purposes
if ($settings["debug"])
imagerectangle($canvas, $m3, $m0,$w-$m1,$h-$m2,
    imagecolorallocate($canvas, 255, 0, 255));

// Figure out the fit
$drawWidth = $w - $m3 - $m1;
$drawHeight = $h - $m0 - $m2;
$aspectRatio = $drawWidth / $drawHeight;
$bestFit = findBestFit($drawWidth, $drawHeight, $num_kanji);

// Find the y-offset, needed to perfectly align the text.
$y_offset = floor($bestFit["fontSize"]) * 1.2;

// Draw each character
for ($i = 0; $i < $num_kanji; $i++) {
    $character = mb_substr($all_kanji, $i, 1);
    $color = getColor($character);

    $y = $m0 + floor($i / $bestFit["w"]) * $bestFit["charHeight"];
    $x = $m3 + ($i % $bestFit["w"]) * $bestFit["charWidth"];

    // Draw the character
    imagettftext($canvas, $bestFit["fontSize"], 0, $x, $y + $y_offset, $color, $settings["fontfile"], $character);
}

// Output and free from memory
imagepng($canvas, "wallpaper.png");
system("osascript -e 'tell application \"Finder\" to set desktop picture to POSIX file \"".dirname(__FILE__)."/wallpaper.png\"'");
imagedestroy($canvas);

print "\nFinished!\n";

// Helper Functions
function hex_to_array($hex) {
    $array = [];

    // Keep only alphanumeric characters
    $hex = preg_replace("/[^a-zA-Z0-9]+/", "", $hex);

    // Grab each two characters, and add to the array
    for ($i = 0; $i < 3; $i++) {
        $array[] = intval(base_convert(substr($hex, $i*2, 2), "16", "10"));
    }

    return $array;
}

function getColor($character) {
    global $progress_report, $settings;
    if (!isset($progress_report[$character])) {
        return $settings["a_colors"]["unseen"];
    }

    if (!isset($progress_report[$character]["user_specific"]) || !is_array($progress_report[$character]["user_specific"])) {
        return $settings["a_colors"]["unseen"];
    }

    return $settings["a_colors"][$progress_report[$character]["user_specific"]["srs"]];
}

function findBestFit($w, $h, $elementsToFit) {

    global $settings;
    $sqrt = ceil(sqrt($elementsToFit)) + 1;

    $aspectRatio = $w / $h;

    $y = ceil($sqrt / ((1 + $aspectRatio)/2));
    $x = ceil($elementsToFit / $y);

    $charWidth = $w / $x;
    $charHeight = $h / $y;
    $fontSize = min($charWidth, $charHeight);
    $totalArea = $w * $h;
    $coveredArea = $elementsToFit * pow($fontSize, 2);
    $fit = $coveredArea / $totalArea;

    return [
        "fit" => $fit,
        "w" => $x,
        "h" => $y,
        "fontSize" => $fontSize * $settings["fontAdjustment"],
        "charWidth" => $charWidth,
        "charHeight" => $charHeight,
    ];
}
?>

To test that it works, double-click on the code file. If you get an error such as WaniKani Wallpaper.command could not be executed because you do not have appropriate access privileges., then follow step 4.1. If you don’t get this error and your wallpaper updated, then just skip to step 5.

4.1) Make the code file executable

Open Terminal, and run the following command, except with the path to your code file. If you created your code file on the desktop, then the path will be something like “~/Desktop/WaniKani Wallpaper.command”.

chmod a+x "~/Desktop/WaniKani Wallpaper.command"

To test that the code file will execute now, double-click it, and your wallpaper should change.

5) (optional) Create a link to the code file on your desktop

If you placed your code file directly on the desktop, then skip this step.

Click on your code file. From the File menu, select Make Alias. The alias (aka a “shortcut” in Windows) will appear in the same folder. Click and drag the alias to your desktop.

6) Go burn some turtles! :slight_smile:

Just double-click the code file or its alias from step 5 any time you want to update your WaniKani desktop wallpaper.

2 Likes

I’ll let you know

1 Like

That’s neat, it’d be cool to transition it to something that doesn’t depend on the PHP interpreter being installed on the end users machine.

I wasn’t aware of the old plugin, so it’s cool to learn about this. Nice :slight_smile:

1 Like

No bueno:

Parse error: syntax error, unexpected ‘;’ in /Users/aloa/Desktop/WaniKani Wallpaper.command on line 35

logout

Saving session…

…copying shared history…

…saving history…truncating history files…

…completed.

Deleting expired sessions…356 completed.

1 Like

Oh whoops! Thank you for testing it. I had a typo in the Mac-version of the code. I updated it, so please try copying the code again, or just fix the one line that was wrong, fixed here. It was missing a parenthesis at the end.

// Make sure we can find the font file
if (!file_exists($settings["fontfile"])) {

Hi Tombow!

Thank you for your feedback. I agree. I originally wanted to do this using the original executable from the original post, but I had trouble getting that to work. And PHP is my main language and I wanted this for myself as soon as possible, lol. My C++ is a little rough, but if enough people ask for it then I’ll see what I can do about getting the original C++ version to work with some extra features.

Actually, on that note, I’m starting to think of some extra features, like for example, only showing the kanji from your current level and the level before (for study purposes). Can you think of any other feature ideas? I would love to hear them!

Well… now I got this:

Stack trace:

#0 {main}

thrown in /Users/aloa/Desktop/WaniKani Wallpaper.command on line 168

logout

Saving session…

…copying shared history…

…saving history…truncating history files…

…completed.

[Procés completat]

1 Like

It looks I have to install the GD module.
So far I have installed:
xcode-select --install
and now I’m trying:

brew install libgd
cpan install GD

1 Like

Hey Emucat!

GD should actually be installed already with the code you ran to install PHP. Nice thinking, though! I appreciate you looking into this as well :slight_smile:

Line 168 is the line that draws a single character, and since that’s the first time the font file is mentioned I think the error actually has to do with FreeType (which is related to gd) or with finding the font. I was able to somewhat reproduce the error on my computer and fix it, so please try the following.

  1. Download the font again and extract it to the same folder where your code file is. (To the desktop, in your case). Unlike before, do not install the font.

  2. Find this line in the code file – it’s located right above where the kanji characters are listed. Change the line from "fontfile" => "/Library/Fonts/KosugiMaru-Regular.ttf",
    to "fontfile" => realpath("KosugiMaru-Regular.ttf"),
    but adjust the font filename as necessary if you downloaded a different font.

Same error. Actually, if it cannot find the font it gives me another error like: Font not found…

1 Like

i’ve been using the webpage. too lazy to set this all up, but it’s a nice idea :slight_smile:

1 Like

Maybe another approach could be that the script takes the API, puts it in the website, and downloads the wallpaper…

1 Like

I think it’s an issue with Mojave.

Php 7.3 seems to have issues on it

1 Like

@OmukaiAndi, Well, get ready, because this is going to get easier, lol.

1 Like

Hey @emucat, I can’t do that, but I can do something similar. I’ll let you know tomorrow :wink:

1 Like

Still waiting :wink:

1 Like

Lol, I’m still working on it! Here’s a teaser image.

1 Like

Awesome!

Ca it be also set for an iPhone wallpaper?

1 Like