app_Main.py 472 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496
  1. # ###########################################################
  2. # FlatCAM: 2D Post-processing for Manufacturing #
  3. # http://flatcam.org #
  4. # Author: Juan Pablo Caram (c) #
  5. # Date: 2/5/2014 #
  6. # MIT Licence #
  7. # Modified by Marius Stanciu (2019) #
  8. # ###########################################################
  9. import urllib.request
  10. import urllib.parse
  11. import urllib.error
  12. import getopt
  13. import random
  14. import simplejson as json
  15. import shutil
  16. import lzma
  17. from datetime import datetime
  18. import time
  19. import ctypes
  20. import traceback
  21. from shapely.geometry import Point, MultiPolygon
  22. from shapely.ops import unary_union
  23. from io import StringIO
  24. from reportlab.graphics import renderPDF
  25. from reportlab.pdfgen import canvas
  26. from reportlab.lib.units import inch, mm
  27. from reportlab.lib.pagesizes import landscape, portrait
  28. from svglib.svglib import svg2rlg
  29. import gc
  30. from xml.dom.minidom import parseString as parse_xml_string
  31. from multiprocessing.connection import Listener, Client
  32. from multiprocessing import Pool
  33. import socket
  34. # ####################################################################################################################
  35. # ################################### Imports part of FlatCAM #############################################
  36. # ####################################################################################################################
  37. # Various
  38. from appCommon.Common import LoudDict
  39. from appCommon.Common import color_variant
  40. from appCommon.Common import ExclusionAreas
  41. from Bookmark import BookmarkManager
  42. from appDatabase import ToolsDB2
  43. from vispy.gloo.util import _screenshot
  44. from vispy.io import write_png
  45. # FlatCAM defaults (preferences)
  46. from defaults import FlatCAMDefaults
  47. # FlatCAM Objects
  48. from appGUI.preferences.OptionsGroupUI import OptionsGroupUI
  49. from appGUI.preferences.PreferencesUIManager import PreferencesUIManager
  50. from appObjects.ObjectCollection import *
  51. from appObjects.FlatCAMObj import FlatCAMObj
  52. from appObjects.AppObject import AppObject
  53. # FlatCAM Parsing files
  54. from appParsers.ParseExcellon import Excellon
  55. from appParsers.ParseGerber import Gerber
  56. from camlib import to_dict, dict2obj, ET, ParseError, Geometry, CNCjob
  57. # FlatCAM appGUI
  58. from appGUI.PlotCanvas import *
  59. from appGUI.PlotCanvasLegacy import *
  60. from appGUI.MainGUI import *
  61. from appGUI.GUIElements import FCFileSaveDialog, message_dialog, FlatCAMSystemTray, FCInputDialogSlider
  62. # FlatCAM Pre-processors
  63. from appPreProcessor import load_preprocessors
  64. # FlatCAM appEditors
  65. from appEditors.AppGeoEditor import AppGeoEditor
  66. from appEditors.AppExcEditor import AppExcEditor
  67. from appEditors.AppGerberEditor import AppGerberEditor
  68. from appEditors.AppTextEditor import AppTextEditor
  69. from appEditors.appGCodeEditor import AppGCodeEditor
  70. from appParsers.ParseHPGL2 import HPGL2
  71. # FlatCAM Workers
  72. from appProcess import *
  73. from appWorkerStack import WorkerStack
  74. # FlatCAM Tools
  75. from appTools import *
  76. # FlatCAM Translation
  77. import gettext
  78. import appTranslation as fcTranslate
  79. import builtins
  80. if sys.platform == 'win32':
  81. import winreg
  82. from win32comext.shell import shell, shellcon
  83. fcTranslate.apply_language('strings')
  84. if '_' not in builtins.__dict__:
  85. _ = gettext.gettext
  86. class App(QtCore.QObject):
  87. """
  88. The main application class. The constructor starts the GUI and all other classes used by the program.
  89. """
  90. # ###############################################################################################################
  91. # ########################################## App ################################################################
  92. # ###############################################################################################################
  93. # ###############################################################################################################
  94. # ######################################### LOGGING #############################################################
  95. # ###############################################################################################################
  96. log = logging.getLogger('base')
  97. log.setLevel(logging.DEBUG)
  98. # log.setLevel(logging.WARNING)
  99. formatter = logging.Formatter('[%(levelname)s][%(threadName)s] %(message)s')
  100. handler = logging.StreamHandler()
  101. handler.setFormatter(formatter)
  102. log.addHandler(handler)
  103. # ###############################################################################################################
  104. # #################################### Get Cmd Line Options #####################################################
  105. # ###############################################################################################################
  106. cmd_line_shellfile = ''
  107. cmd_line_shellvar = ''
  108. cmd_line_headless = None
  109. cmd_line_help = "FlatCam.py --shellfile=<cmd_line_shellfile>\n" \
  110. "FlatCam.py --shellvar=<1,'C:\\path',23>\n" \
  111. "FlatCam.py --headless=1"
  112. try:
  113. # Multiprocessing pool will spawn additional processes with 'multiprocessing-fork' flag
  114. cmd_line_options, args = getopt.getopt(sys.argv[1:], "h:", ["shellfile=",
  115. "shellvar=",
  116. "headless=",
  117. "multiprocessing-fork="])
  118. except getopt.GetoptError:
  119. print(cmd_line_help)
  120. sys.exit(2)
  121. for opt, arg in cmd_line_options:
  122. if opt == '-h':
  123. print(cmd_line_help)
  124. sys.exit()
  125. elif opt == '--shellfile':
  126. cmd_line_shellfile = arg
  127. elif opt == '--shellvar':
  128. cmd_line_shellvar = arg
  129. elif opt == '--headless':
  130. try:
  131. cmd_line_headless = eval(arg)
  132. except NameError:
  133. pass
  134. # ###############################################################################################################
  135. # ################################### Version and VERSION DATE ##################################################
  136. # ###############################################################################################################
  137. version = "Unstable Version"
  138. # version = 8.994
  139. version_date = "2020/10/30"
  140. beta = True
  141. engine = '3D'
  142. # current date now
  143. date = str(datetime.today()).rpartition('.')[0]
  144. date = ''.join(c for c in date if c not in ':-')
  145. date = date.replace(' ', '_')
  146. # ###############################################################################################################
  147. # ############################################ URLS's ###########################################################
  148. # ###############################################################################################################
  149. # URL for update checks and statistics
  150. version_url = "http://flatcam.org/version"
  151. # App URL
  152. app_url = "http://flatcam.org"
  153. # Manual URL
  154. manual_url = "http://flatcam.org/manual/index.html"
  155. video_url = "https://www.youtube.com/playlist?list=PLVvP2SYRpx-AQgNlfoxw93tXUXon7G94_"
  156. gerber_spec_url = "https://www.ucamco.com/files/downloads/file/81/The_Gerber_File_Format_specification." \
  157. "pdf?7ac957791daba2cdf4c2c913f67a43da"
  158. excellon_spec_url = "https://www.ucamco.com/files/downloads/file/305/the_xnc_file_format_specification.pdf"
  159. bug_report_url = "https://bitbucket.org/jpcgt/flatcam/issues?status=new&status=open"
  160. # this variable will hold the project status
  161. # if True it will mean that the project was modified and not saved
  162. should_we_save = False
  163. # flag is True if saving action has been triggered
  164. save_in_progress = False
  165. # ###############################################################################################################
  166. # ####################################### APP Signals ######################################################
  167. # ###############################################################################################################
  168. # Inform the user
  169. # Handled by: App.info() --> Print on the status bar
  170. inform = QtCore.pyqtSignal([str], [str, bool])
  171. # Handled by: App.info_shell() --> Print on the shell
  172. inform_shell = QtCore.pyqtSignal([str], [str, bool])
  173. app_quit = QtCore.pyqtSignal()
  174. # General purpose background task
  175. worker_task = QtCore.pyqtSignal(dict)
  176. # File opened
  177. # Handled by:
  178. # * register_folder()
  179. # * register_recent()
  180. # Note: Setting the parameters to unicode does not seem
  181. # to have an effect. Then are received as Qstring
  182. # anyway.
  183. # File type and filename
  184. file_opened = QtCore.pyqtSignal(str, str)
  185. # File type and filename
  186. file_saved = QtCore.pyqtSignal(str, str)
  187. # Percentage of progress
  188. progress = QtCore.pyqtSignal(int)
  189. # Emitted when a new object has been added or deleted from/to the collection
  190. object_status_changed = QtCore.pyqtSignal(object, str, str)
  191. message = QtCore.pyqtSignal(str, str, str)
  192. # Emmited when shell command is finished(one command only)
  193. shell_command_finished = QtCore.pyqtSignal(object)
  194. # Emitted when multiprocess pool has been recreated
  195. pool_recreated = QtCore.pyqtSignal(object)
  196. # Emitted when an unhandled exception happens
  197. # in the worker task.
  198. thread_exception = QtCore.pyqtSignal(object)
  199. # used to signal that there are arguments for the app
  200. args_at_startup = QtCore.pyqtSignal(list)
  201. # a reusable signal to replot a list of objects
  202. # should be disconnected after use so it can be reused
  203. replot_signal = pyqtSignal(list)
  204. # signal emitted when jumping
  205. jump_signal = pyqtSignal(tuple)
  206. # signal emitted when jumping
  207. locate_signal = pyqtSignal(tuple, str)
  208. # close app signal
  209. close_app_signal = pyqtSignal()
  210. # will perform the cleanup operation after a Graceful Exit
  211. # usefull for the NCC Tool and Paint Tool where some progressive plotting might leave
  212. # graphic residues behind
  213. cleanup = pyqtSignal()
  214. def __init__(self, user_defaults=True):
  215. """
  216. Starts the application.
  217. :return: app
  218. :rtype: App
  219. """
  220. super().__init__()
  221. App.log.info("FlatCAM Starting...")
  222. # ############################################################################################################
  223. # ################# Setup the listening thread for another instance launching with args ######################
  224. # ############################################################################################################
  225. if sys.platform == 'win32' or sys.platform == 'linux':
  226. # make sure the thread is stored by using a self. otherwise it's garbage collected
  227. self.listen_th = QtCore.QThread()
  228. self.listen_th.start(priority=QtCore.QThread.LowestPriority)
  229. self.new_launch = ArgsThread()
  230. self.new_launch.open_signal[list].connect(self.on_startup_args)
  231. self.new_launch.moveToThread(self.listen_th)
  232. self.new_launch.start.emit()
  233. # ############################################################################################################
  234. # ########################################## OS-specific #####################################################
  235. # ############################################################################################################
  236. portable = False
  237. # Folder for user settings.
  238. if sys.platform == 'win32':
  239. if platform.architecture()[0] == '32bit':
  240. App.log.debug("Win32!")
  241. else:
  242. App.log.debug("Win64!")
  243. # #######################################################################################################
  244. # ####### CONFIG FILE WITH PARAMETERS REGARDING PORTABILITY #############################################
  245. # #######################################################################################################
  246. config_file = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config\\configuration.txt'
  247. try:
  248. with open(config_file, 'r'):
  249. pass
  250. except FileNotFoundError:
  251. config_file = os.path.dirname(os.path.realpath(__file__)) + '\\config\\configuration.txt'
  252. try:
  253. with open(config_file, 'r') as f:
  254. try:
  255. for line in f:
  256. param = str(line).replace('\n', '').rpartition('=')
  257. if param[0] == 'portable':
  258. try:
  259. portable = eval(param[2])
  260. except NameError:
  261. portable = False
  262. if param[0] == 'headless':
  263. if param[2].lower() == 'true':
  264. self.cmd_line_headless = 1
  265. else:
  266. self.cmd_line_headless = None
  267. except Exception as e:
  268. log.debug('App.__init__() -->%s' % str(e))
  269. return
  270. except FileNotFoundError as e:
  271. log.debug(str(e))
  272. pass
  273. if portable is False:
  274. self.data_path = shell.SHGetFolderPath(0, shellcon.CSIDL_APPDATA, None, 0) + '\\FlatCAM'
  275. else:
  276. self.data_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config'
  277. self.os = 'windows'
  278. else: # Linux/Unix/MacOS
  279. self.data_path = os.path.expanduser('~') + '/.FlatCAM'
  280. self.os = 'unix'
  281. # ############################################################################################################
  282. # ################################# Setup folders and files ##################################################
  283. # ############################################################################################################
  284. if not os.path.exists(self.data_path):
  285. os.makedirs(self.data_path)
  286. App.log.debug('Created data folder: ' + self.data_path)
  287. os.makedirs(os.path.join(self.data_path, 'preprocessors'))
  288. App.log.debug('Created data preprocessors folder: ' + os.path.join(self.data_path, 'preprocessors'))
  289. self.preprocessorpaths = os.path.join(self.data_path, 'preprocessors')
  290. if not os.path.exists(self.preprocessorpaths):
  291. os.makedirs(self.preprocessorpaths)
  292. App.log.debug('Created preprocessors folder: ' + self.preprocessorpaths)
  293. # create tools_db.FlatDB file if there is none
  294. try:
  295. f = open(self.data_path + '/tools_db.FlatDB')
  296. f.close()
  297. except IOError:
  298. App.log.debug('Creating empty tools_db.FlatDB')
  299. f = open(self.data_path + '/tools_db.FlatDB', 'w')
  300. json.dump({}, f)
  301. f.close()
  302. # create current_defaults.FlatConfig file if there is none
  303. try:
  304. f = open(self.data_path + '/current_defaults.FlatConfig')
  305. f.close()
  306. except IOError:
  307. App.log.debug('Creating empty current_defaults.FlatConfig')
  308. f = open(self.data_path + '/current_defaults.FlatConfig', 'w')
  309. json.dump({}, f)
  310. f.close()
  311. # the factory defaults are written only once at the first launch of the application after installation
  312. FlatCAMDefaults.save_factory_defaults(os.path.join(self.data_path, "factory_defaults.FlatConfig"), self.version)
  313. # create a recent files json file if there is none
  314. try:
  315. f = open(self.data_path + '/recent.json')
  316. f.close()
  317. except IOError:
  318. App.log.debug('Creating empty recent.json')
  319. f = open(self.data_path + '/recent.json', 'w')
  320. json.dump([], f)
  321. f.close()
  322. # create a recent projects json file if there is none
  323. try:
  324. fp = open(self.data_path + '/recent_projects.json')
  325. fp.close()
  326. except IOError:
  327. App.log.debug('Creating empty recent_projects.json')
  328. fp = open(self.data_path + '/recent_projects.json', 'w')
  329. json.dump([], fp)
  330. fp.close()
  331. # Application directory. CHDIR to it. Otherwise, trying to load GUI icons will fail as their path is relative.
  332. # This will fail under cx_freeze ...
  333. self.app_home = os.path.dirname(os.path.realpath(__file__))
  334. log.debug("Application path is " + self.app_home)
  335. log.debug("Started in " + os.getcwd())
  336. # cx_freeze workaround
  337. if os.path.isfile(self.app_home):
  338. self.app_home = os.path.dirname(self.app_home)
  339. os.chdir(self.app_home)
  340. # ############################################################################################################
  341. # ################################# DEFAULTS - PREFERENCES STORAGE ###########################################
  342. # ############################################################################################################
  343. self.defaults = FlatCAMDefaults(beta=self.beta, version=self.version)
  344. current_defaults_path = os.path.join(self.data_path, "current_defaults.FlatConfig")
  345. if user_defaults:
  346. self.defaults.load(filename=current_defaults_path, inform=self.inform)
  347. if self.defaults['units'] == 'MM':
  348. self.decimals = int(self.defaults['decimals_metric'])
  349. else:
  350. self.decimals = int(self.defaults['decimals_inch'])
  351. if self.defaults["global_gray_icons"] is False:
  352. self.resource_location = 'assets/resources'
  353. else:
  354. self.resource_location = 'assets/resources/dark_resources'
  355. self.current_units = self.defaults['units']
  356. # ###########################################################################################################
  357. # #################################### SETUP OBJECT CLASSES #################################################
  358. # ###########################################################################################################
  359. self.setup_obj_classes()
  360. # ###########################################################################################################
  361. # ###################################### CREATE MULTIPROCESSING POOL #######################################
  362. # ###########################################################################################################
  363. self.pool = Pool()
  364. # ###########################################################################################################
  365. # ###################################### Clear GUI Settings - once at first start ###########################
  366. # ###########################################################################################################
  367. if self.defaults["first_run"] is True:
  368. # on first run clear the previous QSettings, therefore clearing the GUI settings
  369. qsettings = QSettings("Open Source", "FlatCAM")
  370. for key in qsettings.allKeys():
  371. qsettings.remove(key)
  372. # This will write the setting to the platform specific storage.
  373. del qsettings
  374. # ###########################################################################################################
  375. # ###################################### Setting the Splash Screen ##########################################
  376. # ###########################################################################################################
  377. splash_settings = QSettings("Open Source", "FlatCAM")
  378. if splash_settings.contains("splash_screen"):
  379. show_splash = splash_settings.value("splash_screen")
  380. else:
  381. splash_settings.setValue('splash_screen', 1)
  382. # This will write the setting to the platform specific storage.
  383. del splash_settings
  384. show_splash = 1
  385. if show_splash and self.cmd_line_headless != 1:
  386. splash_pix = QtGui.QPixmap(self.resource_location + '/splash.png')
  387. self.splash = QtWidgets.QSplashScreen(splash_pix, Qt.WindowStaysOnTopHint)
  388. # self.splash.setMask(splash_pix.mask())
  389. # move splashscreen to the current monitor
  390. desktop = QtWidgets.QApplication.desktop()
  391. screen = desktop.screenNumber(QtGui.QCursor.pos())
  392. current_screen_center = desktop.availableGeometry(screen).center()
  393. self.splash.move(current_screen_center - self.splash.rect().center())
  394. self.splash.show()
  395. self.splash.showMessage(_("FlatCAM is initializing ..."),
  396. alignment=Qt.AlignBottom | Qt.AlignLeft,
  397. color=QtGui.QColor("gray"))
  398. else:
  399. self.splash = None
  400. show_splash = 0
  401. # ###########################################################################################################
  402. # ######################################### Initialize GUI ##################################################
  403. # ###########################################################################################################
  404. # FlatCAM colors used in plotting
  405. self.FC_light_green = '#BBF268BF'
  406. self.FC_dark_green = '#006E20BF'
  407. self.FC_light_blue = '#a5a5ffbf'
  408. self.FC_dark_blue = '#0000ffbf'
  409. theme_settings = QtCore.QSettings("Open Source", "FlatCAM")
  410. if theme_settings.contains("theme"):
  411. theme = theme_settings.value('theme', type=str)
  412. else:
  413. theme = 'white'
  414. if self.defaults["global_cursor_color_enabled"]:
  415. self.cursor_color_3D = self.defaults["global_cursor_color"]
  416. else:
  417. if theme == 'white':
  418. self.cursor_color_3D = 'black'
  419. else:
  420. self.cursor_color_3D = 'gray'
  421. # update the defaults dict with the setting in QSetting
  422. self.defaults['global_theme'] = theme
  423. self.ui = MainGUI(self)
  424. # set FlatCAM units in the Status bar
  425. self.set_screen_units(self.defaults['units'])
  426. # ###########################################################################################################
  427. # ########################################### AUTOSAVE SETUP ################################################
  428. # ###########################################################################################################
  429. self.block_autosave = False
  430. self.autosave_timer = QtCore.QTimer(self)
  431. self.save_project_auto_update()
  432. self.autosave_timer.timeout.connect(self.save_project_auto)
  433. # ###########################################################################################################
  434. # #################################### LOAD PREPROCESSORS ###################################################
  435. # ###########################################################################################################
  436. # ----------------------------------------- WARNING --------------------------------------------------------
  437. # Preprocessors need to be loaded before the Preferences Manager builds the Preferences
  438. # That's because the number of preprocessors can vary and here the comboboxes are populated
  439. # -----------------------------------------------------------------------------------------------------------
  440. # a dictionary that have as keys the name of the preprocessor files and the value is the class from
  441. # the preprocessor file
  442. self.preprocessors = load_preprocessors(self)
  443. # make sure that always the 'default' preprocessor is the first item in the dictionary
  444. if 'default' in self.preprocessors.keys():
  445. new_ppp_dict = {}
  446. # add the 'default' name first in the dict after removing from the preprocessor's dictionary
  447. default_pp = self.preprocessors.pop('default')
  448. new_ppp_dict['default'] = default_pp
  449. # then add the rest of the keys
  450. for name, val_class in self.preprocessors.items():
  451. new_ppp_dict[name] = val_class
  452. # and now put back the ordered dict with 'default' key first
  453. self.preprocessors = new_ppp_dict
  454. # populate the Preprocessor ComboBoxes in the PREFERENCES
  455. for name in list(self.preprocessors.keys()):
  456. # 'Paste' preprocessors are to be used only in the Solder Paste Dispensing Tool
  457. if name.partition('_')[0] == 'Paste':
  458. self.ui.tools_defaults_form.tools_solderpaste_group.pp_combo.addItem(name)
  459. continue
  460. self.ui.geometry_defaults_form.geometry_opt_group.pp_geometry_name_cb.addItem(name)
  461. # HPGL preprocessor is only for Geometry objects therefore it should not be in the Excellon Preferences
  462. if name == 'hpgl':
  463. continue
  464. self.ui.tools_defaults_form.tools_drill_group.pp_excellon_name_cb.addItem(name)
  465. # add ToolTips for the Preprocessor ComboBoxes in Preferences
  466. for it in range(self.ui.tools_defaults_form.tools_solderpaste_group.pp_combo.count()):
  467. self.ui.tools_defaults_form.tools_solderpaste_group.pp_combo.setItemData(
  468. it, self.ui.tools_defaults_form.tools_solderpaste_group.pp_combo.itemText(it), QtCore.Qt.ToolTipRole)
  469. for it in range(self.ui.geometry_defaults_form.geometry_opt_group.pp_geometry_name_cb.count()):
  470. self.ui.geometry_defaults_form.geometry_opt_group.pp_geometry_name_cb.setItemData(
  471. it, self.ui.geometry_defaults_form.geometry_opt_group.pp_geometry_name_cb.itemText(it),
  472. QtCore.Qt.ToolTipRole)
  473. for it in range(self.ui.tools_defaults_form.tools_drill_group.pp_excellon_name_cb.count()):
  474. self.ui.tools_defaults_form.tools_drill_group.pp_excellon_name_cb.setItemData(
  475. it, self.ui.tools_defaults_form.tools_drill_group.pp_excellon_name_cb.itemText(it),
  476. QtCore.Qt.ToolTipRole)
  477. # ###########################################################################################################
  478. # ##################################### UPDATE PREFERENCES GUI FORMS ########################################
  479. # ###########################################################################################################
  480. self.preferencesUiManager = PreferencesUIManager(defaults=self.defaults, data_path=self.data_path, ui=self.ui,
  481. inform=self.inform)
  482. self.preferencesUiManager.defaults_write_form()
  483. # When the self.defaults dictionary changes will update the Preferences GUI forms
  484. self.defaults.set_change_callback(self.on_defaults_dict_change)
  485. # ###########################################################################################################
  486. # ##################################### FIRST RUN SECTION ###################################################
  487. # ################################ It's done only once after install #####################################
  488. # ###########################################################################################################
  489. if self.defaults["first_run"] is True:
  490. # ONLY AT FIRST STARTUP INIT THE GUI LAYOUT TO 'minimal'
  491. initial_lay = 'minimal'
  492. self.ui.general_defaults_form.general_gui_group.on_layout(lay=initial_lay)
  493. # Set the combobox in Preferences to the current layout
  494. idx = self.ui.general_defaults_form.general_gui_group.layout_combo.findText(initial_lay)
  495. self.ui.general_defaults_form.general_gui_group.layout_combo.setCurrentIndex(idx)
  496. # after the first run, this object should be False
  497. self.defaults["first_run"] = False
  498. self.preferencesUiManager.save_defaults(silent=True)
  499. # ###########################################################################################################
  500. # ############################################ Data #########################################################
  501. # ###########################################################################################################
  502. self.recent = []
  503. self.recent_projects = []
  504. self.clipboard = QtWidgets.QApplication.clipboard()
  505. self.project_filename = None
  506. self.toggle_units_ignore = False
  507. self.main_thread = QtWidgets.QApplication.instance().thread()
  508. # ###########################################################################################################
  509. # ########################################## LOAD LANGUAGES ################################################
  510. # ###########################################################################################################
  511. self.languages = fcTranslate.load_languages()
  512. for name in sorted(self.languages.values()):
  513. self.ui.general_defaults_form.general_app_group.language_cb.addItem(name)
  514. # ###########################################################################################################
  515. # ####################################### APPLY APP LANGUAGE ################################################
  516. # ###########################################################################################################
  517. ret_val = fcTranslate.apply_language('strings')
  518. if ret_val == "no language":
  519. self.inform.emit('[ERROR] %s' % _("Could not find the Language files. The App strings are missing."))
  520. log.debug("Could not find the Language files. The App strings are missing.")
  521. else:
  522. # make the current language the current selection on the language combobox
  523. self.ui.general_defaults_form.general_app_group.language_cb.setCurrentText(ret_val)
  524. log.debug("App.__init__() --> Applied %s language." % str(ret_val).capitalize())
  525. # ###########################################################################################################
  526. # ###################################### CREATE UNIQUE SERIAL NUMBER ########################################
  527. # ###########################################################################################################
  528. chars = 'abcdefghijklmnopqrstuvwxyz0123456789'
  529. if self.defaults['global_serial'] == 0 or len(str(self.defaults['global_serial'])) < 10:
  530. self.defaults['global_serial'] = ''.join([random.choice(chars) for __ in range(20)])
  531. self.preferencesUiManager.save_defaults(silent=True, first_time=True)
  532. self.defaults.propagate_defaults()
  533. # ###########################################################################################################
  534. # ######################################## UPDATE THE OPTIONS ###############################################
  535. # ###########################################################################################################
  536. self.options = LoudDict()
  537. # -----------------------------------------------------------------------------------------------------------
  538. # Update the self.options from the self.defaults
  539. # The self.defaults holds the application defaults while the self.options holds the object defaults
  540. # -----------------------------------------------------------------------------------------------------------
  541. # Copy app defaults to project options
  542. for def_key, def_val in self.defaults.items():
  543. self.options[def_key] = deepcopy(def_val)
  544. self.preferencesUiManager.show_preferences_gui()
  545. # ### End of Data ####
  546. # ###########################################################################################################
  547. # #################################### SETUP OBJECT COLLECTION ##############################################
  548. # ###########################################################################################################
  549. self.collection = ObjectCollection(app=self)
  550. self.ui.project_tab_layout.addWidget(self.collection.view)
  551. self.app_obj = AppObject(app=self)
  552. # ### Adjust tabs width ## ##
  553. # self.collection.view.setMinimumWidth(self.ui.options_scroll_area.widget().sizeHint().width() +
  554. # self.ui.options_scroll_area.verticalScrollBar().sizeHint().width())
  555. self.collection.view.setMinimumWidth(290)
  556. self.log.debug("Finished creating Object Collection.")
  557. # ###########################################################################################################
  558. # ######################################## SETUP Plot Area ##################################################
  559. # ###########################################################################################################
  560. # determine if the Legacy Graphic Engine is to be used or the OpenGL one
  561. if self.defaults["global_graphic_engine"] == '3D':
  562. self.is_legacy = False
  563. else:
  564. self.is_legacy = True
  565. # Event signals disconnect id holders
  566. self.mp = None
  567. self.mm = None
  568. self.mr = None
  569. self.mdc = None
  570. self.mp_zc = None
  571. self.kp = None
  572. # Matplotlib axis
  573. self.axes = None
  574. if show_splash:
  575. self.splash.showMessage(_("FlatCAM is initializing ...\n"
  576. "Canvas initialization started."),
  577. alignment=Qt.AlignBottom | Qt.AlignLeft,
  578. color=QtGui.QColor("gray"))
  579. start_plot_time = time.time() # debug
  580. self.plotcanvas = None
  581. self.app_cursor = None
  582. self.hover_shapes = None
  583. self.log.debug("Setting up canvas: %s" % str(self.defaults["global_graphic_engine"]))
  584. # setup the PlotCanvas
  585. self.on_plotcanvas_setup()
  586. end_plot_time = time.time()
  587. self.used_time = end_plot_time - start_plot_time
  588. self.log.debug("Finished Canvas initialization in %s seconds." % str(self.used_time))
  589. if show_splash:
  590. self.splash.showMessage('%s: %ssec' % (_("FlatCAM is initializing ...\n"
  591. "Canvas initialization started.\n"
  592. "Canvas initialization finished in"), '%.2f' % self.used_time),
  593. alignment=Qt.AlignBottom | Qt.AlignLeft,
  594. color=QtGui.QColor("gray"))
  595. self.ui.splitter.setStretchFactor(1, 2)
  596. # ###########################################################################################################
  597. # ############################################### Worker SETUP ##############################################
  598. # ###########################################################################################################
  599. if self.defaults["global_worker_number"]:
  600. self.workers = WorkerStack(workers_number=int(self.defaults["global_worker_number"]))
  601. else:
  602. self.workers = WorkerStack(workers_number=2)
  603. self.worker_task.connect(self.workers.add_task)
  604. self.log.debug("Finished creating Workers crew.")
  605. # ###########################################################################################################
  606. # ############################################# Activity Monitor ############################################
  607. # ###########################################################################################################
  608. # self.activity_view = FlatCAMActivityView(app=self)
  609. # self.ui.infobar.addWidget(self.activity_view)
  610. self.proc_container = FCVisibleProcessContainer(self.ui.activity_view)
  611. # ###########################################################################################################
  612. # ########################################## Other setups ###################################################
  613. # ###########################################################################################################
  614. # to use for tools like Distance tool who depends on the event sources who are changed inside the appEditors
  615. # depending on from where those tools are called different actions can be done
  616. self.call_source = 'app'
  617. # this is a flag to signal to other tools that the ui tooltab is locked and not accessible
  618. self.tool_tab_locked = False
  619. # decide if to show or hide the Notebook side of the screen at startup
  620. if self.defaults["global_project_at_startup"] is True:
  621. self.ui.splitter.setSizes([1, 1])
  622. else:
  623. self.ui.splitter.setSizes([0, 1])
  624. # Sets up FlatCAMObj, FCProcess and FCProcessContainer.
  625. self.setup_default_properties_tab()
  626. # ###########################################################################################################
  627. # ####################################### Auto-complete KEYWORDS ############################################
  628. # ###########################################################################################################
  629. self.tcl_commands_list = ['add_circle', 'add_poly', 'add_polygon', 'add_polyline', 'add_rectangle',
  630. 'aligndrill', 'aligndrillgrid', 'bbox', 'clear', 'cncjob', 'cutout',
  631. 'del', 'drillcncjob', 'export_dxf', 'edxf', 'export_excellon',
  632. 'export_exc',
  633. 'export_gcode', 'export_gerber', 'export_svg', 'ext', 'exteriors', 'follow',
  634. 'geo_union', 'geocutout', 'get_bounds', 'get_names', 'get_path', 'get_sys', 'help',
  635. 'interiors', 'isolate', 'join_excellon',
  636. 'join_geometry', 'list_sys', 'milld', 'mills', 'milldrills', 'millslots',
  637. 'mirror', 'ncc',
  638. 'ncr', 'new', 'new_geometry', 'non_copper_regions', 'offset',
  639. 'open_dxf', 'open_excellon', 'open_gcode', 'open_gerber', 'open_project', 'open_svg',
  640. 'options', 'origin',
  641. 'paint', 'panelize', 'plot_all', 'plot_objects', 'plot_status', 'quit_flatcam',
  642. 'save', 'save_project',
  643. 'save_sys', 'scale', 'set_active', 'set_origin', 'set_path', 'set_sys',
  644. 'skew', 'subtract_poly', 'subtract_rectangle',
  645. 'version', 'write_gcode'
  646. ]
  647. self.default_keywords = ['Desktop', 'Documents', 'FlatConfig', 'FlatPrj', 'False', 'Marius', 'My Documents',
  648. 'Paste_1',
  649. 'Repetier', 'Roland_MDX_20', 'Users', 'Toolchange_Custom', 'Toolchange_Probe_MACH3',
  650. 'Toolchange_manual', 'True', 'Users',
  651. 'all', 'auto', 'axis',
  652. 'axisoffset', 'box', 'center_x', 'center_y', 'columns', 'combine', 'connect',
  653. 'contour', 'default',
  654. 'depthperpass', 'dia', 'diatol', 'dist', 'drilled_dias', 'drillz', 'dpp',
  655. 'dwelltime', 'extracut_length', 'endxy', 'enz', 'f', 'feedrate',
  656. 'feedrate_z', 'grbl_11', 'GRBL_laser', 'gridoffsety', 'gridx', 'gridy',
  657. 'has_offset', 'holes', 'hpgl', 'iso_type', 'line_xyz', 'margin', 'marlin', 'method',
  658. 'milled_dias', 'minoffset', 'name', 'offset', 'opt_type', 'order',
  659. 'outname', 'overlap', 'passes', 'postamble', 'pp', 'ppname_e', 'ppname_g',
  660. 'preamble', 'radius', 'ref', 'rest', 'rows', 'shellvar_', 'scale_factor',
  661. 'spacing_columns',
  662. 'spacing_rows', 'spindlespeed', 'startz', 'startxy',
  663. 'toolchange_xy', 'toolchangez', 'travelz',
  664. 'tooldia', 'use_threads', 'value',
  665. 'x', 'x0', 'x1', 'y', 'y0', 'y1', 'z_cut', 'z_move'
  666. ]
  667. self.tcl_keywords = [
  668. 'after', 'append', 'apply', 'argc', 'argv', 'argv0', 'array', 'attemptckalloc', 'attemptckrealloc',
  669. 'auto_execok', 'auto_import', 'auto_load', 'auto_mkindex', 'auto_path', 'auto_qualify', 'auto_reset',
  670. 'bgerror', 'binary', 'break', 'case', 'catch', 'cd', 'chan', 'ckalloc', 'ckfree', 'ckrealloc', 'clock',
  671. 'close', 'concat', 'continue', 'coroutine', 'dde', 'dict', 'encoding', 'env', 'eof', 'error', 'errorCode',
  672. 'errorInfo', 'eval', 'exec', 'exit', 'expr', 'fblocked', 'fconfigure', 'fcopy', 'file', 'fileevent',
  673. 'filename', 'flush', 'for', 'foreach', 'format', 'gets', 'glob', 'global', 'history', 'http', 'if', 'incr',
  674. 'info', 'interp', 'join', 'lappend', 'lassign', 'lindex', 'linsert', 'list', 'llength', 'load', 'lrange',
  675. 'lrepeat', 'lreplace', 'lreverse', 'lsearch', 'lset', 'lsort', 'mathfunc', 'mathop', 'memory', 'msgcat',
  676. 'my', 'namespace', 'next', 'nextto', 'open', 'package', 'parray', 'pid', 'pkg_mkIndex', 'platform',
  677. 'proc', 'puts', 'pwd', 're_syntax', 'read', 'refchan', 'regexp', 'registry', 'regsub', 'rename', 'return',
  678. 'safe', 'scan', 'seek', 'self', 'set', 'socket', 'source', 'split', 'string', 'subst', 'switch',
  679. 'tailcall', 'Tcl', 'Tcl_Access', 'Tcl_AddErrorInfo', 'Tcl_AddObjErrorInfo', 'Tcl_AlertNotifier',
  680. 'Tcl_Alloc', 'Tcl_AllocHashEntryProc', 'Tcl_AllocStatBuf', 'Tcl_AllowExceptions', 'Tcl_AppendAllObjTypes',
  681. 'Tcl_AppendElement', 'Tcl_AppendExportList', 'Tcl_AppendFormatToObj', 'Tcl_AppendLimitedToObj',
  682. 'Tcl_AppendObjToErrorInfo', 'Tcl_AppendObjToObj', 'Tcl_AppendPrintfToObj', 'Tcl_AppendResult',
  683. 'Tcl_AppendResultVA', 'Tcl_AppendStringsToObj', 'Tcl_AppendStringsToObjVA', 'Tcl_AppendToObj',
  684. 'Tcl_AppendUnicodeToObj', 'Tcl_AppInit', 'Tcl_AppInitProc', 'Tcl_ArgvInfo', 'Tcl_AsyncCreate',
  685. 'Tcl_AsyncDelete', 'Tcl_AsyncInvoke', 'Tcl_AsyncMark', 'Tcl_AsyncProc', 'Tcl_AsyncReady',
  686. 'Tcl_AttemptAlloc', 'Tcl_AttemptRealloc', 'Tcl_AttemptSetObjLength', 'Tcl_BackgroundError',
  687. 'Tcl_BackgroundException', 'Tcl_Backslash', 'Tcl_BadChannelOption', 'Tcl_CallWhenDeleted', 'Tcl_Canceled',
  688. 'Tcl_CancelEval', 'Tcl_CancelIdleCall', 'Tcl_ChannelBlockModeProc', 'Tcl_ChannelBuffered',
  689. 'Tcl_ChannelClose2Proc', 'Tcl_ChannelCloseProc', 'Tcl_ChannelFlushProc', 'Tcl_ChannelGetHandleProc',
  690. 'Tcl_ChannelGetOptionProc', 'Tcl_ChannelHandlerProc', 'Tcl_ChannelInputProc', 'Tcl_ChannelName',
  691. 'Tcl_ChannelOutputProc', 'Tcl_ChannelProc', 'Tcl_ChannelSeekProc', 'Tcl_ChannelSetOptionProc',
  692. 'Tcl_ChannelThreadActionProc', 'Tcl_ChannelTruncateProc', 'Tcl_ChannelType', 'Tcl_ChannelVersion',
  693. 'Tcl_ChannelWatchProc', 'Tcl_ChannelWideSeekProc', 'Tcl_Chdir', 'Tcl_ClassGetMetadata',
  694. 'Tcl_ClassSetConstructor', 'Tcl_ClassSetDestructor', 'Tcl_ClassSetMetadata', 'Tcl_ClearChannelHandlers',
  695. 'Tcl_CloneProc', 'Tcl_Close', 'Tcl_CloseProc', 'Tcl_CmdDeleteProc', 'Tcl_CmdInfo',
  696. 'Tcl_CmdObjTraceDeleteProc', 'Tcl_CmdObjTraceProc', 'Tcl_CmdProc', 'Tcl_CmdTraceProc',
  697. 'Tcl_CommandComplete', 'Tcl_CommandTraceInfo', 'Tcl_CommandTraceProc', 'Tcl_CompareHashKeysProc',
  698. 'Tcl_Concat', 'Tcl_ConcatObj', 'Tcl_ConditionFinalize', 'Tcl_ConditionNotify', 'Tcl_ConditionWait',
  699. 'Tcl_Config', 'Tcl_ConvertCountedElement', 'Tcl_ConvertElement', 'Tcl_ConvertToType',
  700. 'Tcl_CopyObjectInstance', 'Tcl_CreateAlias', 'Tcl_CreateAliasObj', 'Tcl_CreateChannel',
  701. 'Tcl_CreateChannelHandler', 'Tcl_CreateCloseHandler', 'Tcl_CreateCommand', 'Tcl_CreateEncoding',
  702. 'Tcl_CreateEnsemble', 'Tcl_CreateEventSource', 'Tcl_CreateExitHandler', 'Tcl_CreateFileHandler',
  703. 'Tcl_CreateHashEntry', 'Tcl_CreateInterp', 'Tcl_CreateMathFunc', 'Tcl_CreateNamespace',
  704. 'Tcl_CreateObjCommand', 'Tcl_CreateObjTrace', 'Tcl_CreateSlave', 'Tcl_CreateThread',
  705. 'Tcl_CreateThreadExitHandler', 'Tcl_CreateTimerHandler', 'Tcl_CreateTrace',
  706. 'Tcl_CutChannel', 'Tcl_DecrRefCount', 'Tcl_DeleteAssocData', 'Tcl_DeleteChannelHandler',
  707. 'Tcl_DeleteCloseHandler', 'Tcl_DeleteCommand', 'Tcl_DeleteCommandFromToken', 'Tcl_DeleteEvents',
  708. 'Tcl_DeleteEventSource', 'Tcl_DeleteExitHandler', 'Tcl_DeleteFileHandler', 'Tcl_DeleteHashEntry',
  709. 'Tcl_DeleteHashTable', 'Tcl_DeleteInterp', 'Tcl_DeleteNamespace', 'Tcl_DeleteThreadExitHandler',
  710. 'Tcl_DeleteTimerHandler', 'Tcl_DeleteTrace', 'Tcl_DetachChannel', 'Tcl_DetachPids', 'Tcl_DictObjDone',
  711. 'Tcl_DictObjFirst', 'Tcl_DictObjGet', 'Tcl_DictObjNext', 'Tcl_DictObjPut', 'Tcl_DictObjPutKeyList',
  712. 'Tcl_DictObjRemove', 'Tcl_DictObjRemoveKeyList', 'Tcl_DictObjSize', 'Tcl_DiscardInterpState',
  713. 'Tcl_DiscardResult', 'Tcl_DontCallWhenDeleted', 'Tcl_DoOneEvent', 'Tcl_DoWhenIdle',
  714. 'Tcl_DriverBlockModeProc', 'Tcl_DriverClose2Proc', 'Tcl_DriverCloseProc', 'Tcl_DriverFlushProc',
  715. 'Tcl_DriverGetHandleProc', 'Tcl_DriverGetOptionProc', 'Tcl_DriverHandlerProc', 'Tcl_DriverInputProc',
  716. 'Tcl_DriverOutputProc', 'Tcl_DriverSeekProc', 'Tcl_DriverSetOptionProc', 'Tcl_DriverThreadActionProc',
  717. 'Tcl_DriverTruncateProc', 'Tcl_DriverWatchProc', 'Tcl_DriverWideSeekProc', 'Tcl_DStringAppend',
  718. 'Tcl_DStringAppendElement', 'Tcl_DStringEndSublist', 'Tcl_DStringFree', 'Tcl_DStringGetResult',
  719. 'Tcl_DStringInit', 'Tcl_DStringLength', 'Tcl_DStringResult', 'Tcl_DStringSetLength',
  720. 'Tcl_DStringStartSublist', 'Tcl_DStringTrunc', 'Tcl_DStringValue', 'Tcl_DumpActiveMemory',
  721. 'Tcl_DupInternalRepProc', 'Tcl_DuplicateObj', 'Tcl_EncodingConvertProc', 'Tcl_EncodingFreeProc',
  722. 'Tcl_EncodingType', 'tcl_endOfWord', 'Tcl_Eof', 'Tcl_ErrnoId', 'Tcl_ErrnoMsg', 'Tcl_Eval', 'Tcl_EvalEx',
  723. 'Tcl_EvalFile', 'Tcl_EvalObjEx', 'Tcl_EvalObjv', 'Tcl_EvalTokens', 'Tcl_EvalTokensStandard', 'Tcl_Event',
  724. 'Tcl_EventCheckProc', 'Tcl_EventDeleteProc', 'Tcl_EventProc', 'Tcl_EventSetupProc', 'Tcl_EventuallyFree',
  725. 'Tcl_Exit', 'Tcl_ExitProc', 'Tcl_ExitThread', 'Tcl_Export', 'Tcl_ExposeCommand', 'Tcl_ExprBoolean',
  726. 'Tcl_ExprBooleanObj', 'Tcl_ExprDouble', 'Tcl_ExprDoubleObj', 'Tcl_ExprLong', 'Tcl_ExprLongObj',
  727. 'Tcl_ExprObj', 'Tcl_ExprString', 'Tcl_ExternalToUtf', 'Tcl_ExternalToUtfDString', 'Tcl_FileProc',
  728. 'Tcl_Filesystem', 'Tcl_Finalize', 'Tcl_FinalizeNotifier', 'Tcl_FinalizeThread', 'Tcl_FindCommand',
  729. 'Tcl_FindEnsemble', 'Tcl_FindExecutable', 'Tcl_FindHashEntry', 'tcl_findLibrary', 'Tcl_FindNamespace',
  730. 'Tcl_FirstHashEntry', 'Tcl_Flush', 'Tcl_ForgetImport', 'Tcl_Format', 'Tcl_FreeHashEntryProc',
  731. 'Tcl_FreeInternalRepProc', 'Tcl_FreeParse', 'Tcl_FreeProc', 'Tcl_FreeResult',
  732. 'Tcl_Free·\xa0Tcl_FreeEncoding', 'Tcl_FSAccess', 'Tcl_FSAccessProc', 'Tcl_FSChdir',
  733. 'Tcl_FSChdirProc', 'Tcl_FSConvertToPathType', 'Tcl_FSCopyDirectory', 'Tcl_FSCopyDirectoryProc',
  734. 'Tcl_FSCopyFile', 'Tcl_FSCopyFileProc', 'Tcl_FSCreateDirectory', 'Tcl_FSCreateDirectoryProc',
  735. 'Tcl_FSCreateInternalRepProc', 'Tcl_FSData', 'Tcl_FSDeleteFile', 'Tcl_FSDeleteFileProc',
  736. 'Tcl_FSDupInternalRepProc', 'Tcl_FSEqualPaths', 'Tcl_FSEvalFile', 'Tcl_FSEvalFileEx',
  737. 'Tcl_FSFileAttrsGet', 'Tcl_FSFileAttrsGetProc', 'Tcl_FSFileAttrsSet', 'Tcl_FSFileAttrsSetProc',
  738. 'Tcl_FSFileAttrStrings', 'Tcl_FSFileSystemInfo', 'Tcl_FSFilesystemPathTypeProc',
  739. 'Tcl_FSFilesystemSeparatorProc', 'Tcl_FSFreeInternalRepProc', 'Tcl_FSGetCwd', 'Tcl_FSGetCwdProc',
  740. 'Tcl_FSGetFileSystemForPath', 'Tcl_FSGetInternalRep', 'Tcl_FSGetNativePath', 'Tcl_FSGetNormalizedPath',
  741. 'Tcl_FSGetPathType', 'Tcl_FSGetTranslatedPath', 'Tcl_FSGetTranslatedStringPath',
  742. 'Tcl_FSInternalToNormalizedProc', 'Tcl_FSJoinPath', 'Tcl_FSJoinToPath', 'Tcl_FSLinkProc',
  743. 'Tcl_FSLink·\xa0Tcl_FSListVolumes', 'Tcl_FSListVolumesProc', 'Tcl_FSLoadFile', 'Tcl_FSLoadFileProc',
  744. 'Tcl_FSLstat', 'Tcl_FSLstatProc', 'Tcl_FSMatchInDirectory', 'Tcl_FSMatchInDirectoryProc',
  745. 'Tcl_FSMountsChanged', 'Tcl_FSNewNativePath', 'Tcl_FSNormalizePathProc', 'Tcl_FSOpenFileChannel',
  746. 'Tcl_FSOpenFileChannelProc', 'Tcl_FSPathInFilesystemProc', 'Tcl_FSPathSeparator', 'Tcl_FSRegister',
  747. 'Tcl_FSRemoveDirectory', 'Tcl_FSRemoveDirectoryProc', 'Tcl_FSRenameFile', 'Tcl_FSRenameFileProc',
  748. 'Tcl_FSSplitPath', 'Tcl_FSStat', 'Tcl_FSStatProc', 'Tcl_FSUnloadFile', 'Tcl_FSUnloadFileProc',
  749. 'Tcl_FSUnregister', 'Tcl_FSUtime', 'Tcl_FSUtimeProc', 'Tcl_GetAccessTimeFromStat', 'Tcl_GetAlias',
  750. 'Tcl_GetAliasObj', 'Tcl_GetAssocData', 'Tcl_GetBignumFromObj', 'Tcl_GetBlocksFromStat',
  751. 'Tcl_GetBlockSizeFromStat', 'Tcl_GetBoolean', 'Tcl_GetBooleanFromObj', 'Tcl_GetByteArrayFromObj',
  752. 'Tcl_GetChangeTimeFromStat', 'Tcl_GetChannel', 'Tcl_GetChannelBufferSize', 'Tcl_GetChannelError',
  753. 'Tcl_GetChannelErrorInterp', 'Tcl_GetChannelHandle', 'Tcl_GetChannelInstanceData', 'Tcl_GetChannelMode',
  754. 'Tcl_GetChannelName', 'Tcl_GetChannelNames', 'Tcl_GetChannelNamesEx', 'Tcl_GetChannelOption',
  755. 'Tcl_GetChannelThread', 'Tcl_GetChannelType', 'Tcl_GetCharLength', 'Tcl_GetClassAsObject',
  756. 'Tcl_GetCommandFromObj', 'Tcl_GetCommandFullName', 'Tcl_GetCommandInfo', 'Tcl_GetCommandInfoFromToken',
  757. 'Tcl_GetCommandName', 'Tcl_GetCurrentNamespace', 'Tcl_GetCurrentThread', 'Tcl_GetCwd',
  758. 'Tcl_GetDefaultEncodingDir', 'Tcl_GetDeviceTypeFromStat', 'Tcl_GetDouble', 'Tcl_GetDoubleFromObj',
  759. 'Tcl_GetEncoding', 'Tcl_GetEncodingFromObj', 'Tcl_GetEncodingName', 'Tcl_GetEncodingNameFromEnvironment',
  760. 'Tcl_GetEncodingNames', 'Tcl_GetEncodingSearchPath', 'Tcl_GetEnsembleFlags', 'Tcl_GetEnsembleMappingDict',
  761. 'Tcl_GetEnsembleNamespace', 'Tcl_GetEnsembleParameterList', 'Tcl_GetEnsembleSubcommandList',
  762. 'Tcl_GetEnsembleUnknownHandler', 'Tcl_GetErrno', 'Tcl_GetErrorLine', 'Tcl_GetFSDeviceFromStat',
  763. 'Tcl_GetFSInodeFromStat', 'Tcl_GetGlobalNamespace', 'Tcl_GetGroupIdFromStat', 'Tcl_GetHashKey',
  764. 'Tcl_GetHashValue', 'Tcl_GetHostName', 'Tcl_GetIndexFromObj', 'Tcl_GetIndexFromObjStruct', 'Tcl_GetInt',
  765. 'Tcl_GetInterpPath', 'Tcl_GetIntFromObj', 'Tcl_GetLinkCountFromStat', 'Tcl_GetLongFromObj',
  766. 'Tcl_GetMaster', 'Tcl_GetMathFuncInfo', 'Tcl_GetModeFromStat', 'Tcl_GetModificationTimeFromStat',
  767. 'Tcl_GetNameOfExecutable', 'Tcl_GetNamespaceUnknownHandler', 'Tcl_GetObjectAsClass', 'Tcl_GetObjectCommand',
  768. 'Tcl_GetObjectFromObj', 'Tcl_GetObjectName', 'Tcl_GetObjectNamespace', 'Tcl_GetObjResult', 'Tcl_GetObjType',
  769. 'Tcl_GetOpenFile', 'Tcl_GetPathType', 'Tcl_GetRange', 'Tcl_GetRegExpFromObj', 'Tcl_GetReturnOptions',
  770. 'Tcl_Gets', 'Tcl_GetServiceMode', 'Tcl_GetSizeFromStat', 'Tcl_GetSlave', 'Tcl_GetsObj',
  771. 'Tcl_GetStackedChannel', 'Tcl_GetStartupScript', 'Tcl_GetStdChannel', 'Tcl_GetString',
  772. 'Tcl_GetStringFromObj', 'Tcl_GetStringResult', 'Tcl_GetThreadData', 'Tcl_GetTime', 'Tcl_GetTopChannel',
  773. 'Tcl_GetUniChar', 'Tcl_GetUnicode', 'Tcl_GetUnicodeFromObj', 'Tcl_GetUserIdFromStat', 'Tcl_GetVar',
  774. 'Tcl_GetVar2', 'Tcl_GetVar2Ex', 'Tcl_GetVersion', 'Tcl_GetWideIntFromObj', 'Tcl_GlobalEval',
  775. 'Tcl_GlobalEvalObj', 'Tcl_GlobTypeData', 'Tcl_HashKeyType', 'Tcl_HashStats', 'Tcl_HideCommand',
  776. 'Tcl_IdleProc', 'Tcl_Import', 'Tcl_IncrRefCount', 'Tcl_Init', 'Tcl_InitCustomHashTable',
  777. 'Tcl_InitHashTable', 'Tcl_InitMemory', 'Tcl_InitNotifier', 'Tcl_InitObjHashTable', 'Tcl_InitStubs',
  778. 'Tcl_InputBlocked', 'Tcl_InputBuffered', 'tcl_interactive', 'Tcl_Interp', 'Tcl_InterpActive',
  779. 'Tcl_InterpDeleted', 'Tcl_InterpDeleteProc', 'Tcl_InvalidateStringRep', 'Tcl_IsChannelExisting',
  780. 'Tcl_IsChannelRegistered', 'Tcl_IsChannelShared', 'Tcl_IsEnsemble', 'Tcl_IsSafe', 'Tcl_IsShared',
  781. 'Tcl_IsStandardChannel', 'Tcl_JoinPath', 'Tcl_JoinThread', 'tcl_library', 'Tcl_LimitAddHandler',
  782. 'Tcl_LimitCheck', 'Tcl_LimitExceeded', 'Tcl_LimitGetCommands', 'Tcl_LimitGetGranularity',
  783. 'Tcl_LimitGetTime', 'Tcl_LimitHandlerDeleteProc', 'Tcl_LimitHandlerProc', 'Tcl_LimitReady',
  784. 'Tcl_LimitRemoveHandler', 'Tcl_LimitSetCommands', 'Tcl_LimitSetGranularity', 'Tcl_LimitSetTime',
  785. 'Tcl_LimitTypeEnabled', 'Tcl_LimitTypeExceeded', 'Tcl_LimitTypeReset', 'Tcl_LimitTypeSet',
  786. 'Tcl_LinkVar', 'Tcl_ListMathFuncs', 'Tcl_ListObjAppendElement', 'Tcl_ListObjAppendList',
  787. 'Tcl_ListObjGetElements', 'Tcl_ListObjIndex', 'Tcl_ListObjLength', 'Tcl_ListObjReplace',
  788. 'Tcl_LogCommandInfo', 'Tcl_Main', 'Tcl_MainLoopProc', 'Tcl_MakeFileChannel', 'Tcl_MakeSafe',
  789. 'Tcl_MakeTcpClientChannel', 'Tcl_MathProc', 'TCL_MEM_DEBUG', 'Tcl_Merge', 'Tcl_MethodCallProc',
  790. 'Tcl_MethodDeclarerClass', 'Tcl_MethodDeclarerObject', 'Tcl_MethodDeleteProc', 'Tcl_MethodIsPublic',
  791. 'Tcl_MethodIsType', 'Tcl_MethodName', 'Tcl_MethodType', 'Tcl_MutexFinalize', 'Tcl_MutexLock',
  792. 'Tcl_MutexUnlock', 'Tcl_NamespaceDeleteProc', 'Tcl_NewBignumObj', 'Tcl_NewBooleanObj',
  793. 'Tcl_NewByteArrayObj', 'Tcl_NewDictObj', 'Tcl_NewDoubleObj', 'Tcl_NewInstanceMethod', 'Tcl_NewIntObj',
  794. 'Tcl_NewListObj', 'Tcl_NewLongObj', 'Tcl_NewMethod', 'Tcl_NewObj', 'Tcl_NewObjectInstance',
  795. 'Tcl_NewStringObj', 'Tcl_NewUnicodeObj', 'Tcl_NewWideIntObj', 'Tcl_NextHashEntry', 'tcl_nonwordchars',
  796. 'Tcl_NotifierProcs', 'Tcl_NotifyChannel', 'Tcl_NRAddCallback', 'Tcl_NRCallObjProc', 'Tcl_NRCmdSwap',
  797. 'Tcl_NRCreateCommand', 'Tcl_NREvalObj', 'Tcl_NREvalObjv', 'Tcl_NumUtfChars', 'Tcl_Obj', 'Tcl_ObjCmdProc',
  798. 'Tcl_ObjectContextInvokeNext', 'Tcl_ObjectContextIsFiltering', 'Tcl_ObjectContextMethod',
  799. 'Tcl_ObjectContextObject', 'Tcl_ObjectContextSkippedArgs', 'Tcl_ObjectDeleted', 'Tcl_ObjectGetMetadata',
  800. 'Tcl_ObjectGetMethodNameMapper', 'Tcl_ObjectMapMethodNameProc', 'Tcl_ObjectMetadataDeleteProc',
  801. 'Tcl_ObjectSetMetadata', 'Tcl_ObjectSetMethodNameMapper', 'Tcl_ObjGetVar2', 'Tcl_ObjPrintf',
  802. 'Tcl_ObjSetVar2', 'Tcl_ObjType', 'Tcl_OpenCommandChannel', 'Tcl_OpenFileChannel', 'Tcl_OpenTcpClient',
  803. 'Tcl_OpenTcpServer', 'Tcl_OutputBuffered', 'Tcl_PackageInitProc', 'Tcl_PackageUnloadProc', 'Tcl_Panic',
  804. 'Tcl_PanicProc', 'Tcl_PanicVA', 'Tcl_ParseArgsObjv', 'Tcl_ParseBraces', 'Tcl_ParseCommand', 'Tcl_ParseExpr',
  805. 'Tcl_ParseQuotedString', 'Tcl_ParseVar', 'Tcl_ParseVarName', 'tcl_patchLevel', 'tcl_pkgPath',
  806. 'Tcl_PkgPresent', 'Tcl_PkgPresentEx', 'Tcl_PkgProvide', 'Tcl_PkgProvideEx', 'Tcl_PkgRequire',
  807. 'Tcl_PkgRequireEx', 'Tcl_PkgRequireProc', 'tcl_platform', 'Tcl_PosixError', 'tcl_precision',
  808. 'Tcl_Preserve', 'Tcl_PrintDouble', 'Tcl_PutEnv', 'Tcl_QueryTimeProc', 'Tcl_QueueEvent', 'tcl_rcFileName',
  809. 'Tcl_Read', 'Tcl_ReadChars', 'Tcl_ReadRaw', 'Tcl_Realloc', 'Tcl_ReapDetachedProcs', 'Tcl_RecordAndEval',
  810. 'Tcl_RecordAndEvalObj', 'Tcl_RegExpCompile', 'Tcl_RegExpExec', 'Tcl_RegExpExecObj', 'Tcl_RegExpGetInfo',
  811. 'Tcl_RegExpIndices', 'Tcl_RegExpInfo', 'Tcl_RegExpMatch', 'Tcl_RegExpMatchObj', 'Tcl_RegExpRange',
  812. 'Tcl_RegisterChannel', 'Tcl_RegisterConfig', 'Tcl_RegisterObjType', 'Tcl_Release', 'Tcl_ResetResult',
  813. 'Tcl_RestoreInterpState', 'Tcl_RestoreResult', 'Tcl_SaveInterpState', 'Tcl_SaveResult', 'Tcl_ScaleTimeProc',
  814. 'Tcl_ScanCountedElement', 'Tcl_ScanElement', 'Tcl_Seek', 'Tcl_ServiceAll', 'Tcl_ServiceEvent',
  815. 'Tcl_ServiceModeHook', 'Tcl_SetAssocData', 'Tcl_SetBignumObj', 'Tcl_SetBooleanObj',
  816. 'Tcl_SetByteArrayLength', 'Tcl_SetByteArrayObj', 'Tcl_SetChannelBufferSize', 'Tcl_SetChannelError',
  817. 'Tcl_SetChannelErrorInterp', 'Tcl_SetChannelOption', 'Tcl_SetCommandInfo', 'Tcl_SetCommandInfoFromToken',
  818. 'Tcl_SetDefaultEncodingDir', 'Tcl_SetDoubleObj', 'Tcl_SetEncodingSearchPath', 'Tcl_SetEnsembleFlags',
  819. 'Tcl_SetEnsembleMappingDict', 'Tcl_SetEnsembleParameterList', 'Tcl_SetEnsembleSubcommandList',
  820. 'Tcl_SetEnsembleUnknownHandler', 'Tcl_SetErrno', 'Tcl_SetErrorCode', 'Tcl_SetErrorCodeVA',
  821. 'Tcl_SetErrorLine', 'Tcl_SetExitProc', 'Tcl_SetFromAnyProc', 'Tcl_SetHashValue', 'Tcl_SetIntObj',
  822. 'Tcl_SetListObj', 'Tcl_SetLongObj', 'Tcl_SetMainLoop', 'Tcl_SetMaxBlockTime',
  823. 'Tcl_SetNamespaceUnknownHandler', 'Tcl_SetNotifier', 'Tcl_SetObjErrorCode', 'Tcl_SetObjLength',
  824. 'Tcl_SetObjResult', 'Tcl_SetPanicProc', 'Tcl_SetRecursionLimit', 'Tcl_SetResult', 'Tcl_SetReturnOptions',
  825. 'Tcl_SetServiceMode', 'Tcl_SetStartupScript', 'Tcl_SetStdChannel', 'Tcl_SetStringObj',
  826. 'Tcl_SetSystemEncoding', 'Tcl_SetTimeProc', 'Tcl_SetTimer', 'Tcl_SetUnicodeObj', 'Tcl_SetVar',
  827. 'Tcl_SetVar2', 'Tcl_SetVar2Ex', 'Tcl_SetWideIntObj', 'Tcl_SignalId', 'Tcl_SignalMsg', 'Tcl_Sleep',
  828. 'Tcl_SourceRCFile', 'Tcl_SpliceChannel', 'Tcl_SplitList', 'Tcl_SplitPath', 'Tcl_StackChannel',
  829. 'Tcl_StandardChannels', 'tcl_startOfNextWord', 'tcl_startOfPreviousWord', 'Tcl_Stat', 'Tcl_StaticPackage',
  830. 'Tcl_StringCaseMatch', 'Tcl_StringMatch', 'Tcl_SubstObj', 'Tcl_TakeBignumFromObj', 'Tcl_TcpAcceptProc',
  831. 'Tcl_Tell', 'Tcl_ThreadAlert', 'Tcl_ThreadQueueEvent', 'Tcl_Time', 'Tcl_TimerProc', 'Tcl_Token',
  832. 'Tcl_TraceCommand', 'tcl_traceCompile', 'tcl_traceEval', 'Tcl_TraceVar', 'Tcl_TraceVar2',
  833. 'Tcl_TransferResult', 'Tcl_TranslateFileName', 'Tcl_TruncateChannel', 'Tcl_Ungets', 'Tcl_UniChar',
  834. 'Tcl_UniCharAtIndex', 'Tcl_UniCharCaseMatch', 'Tcl_UniCharIsAlnum', 'Tcl_UniCharIsAlpha',
  835. 'Tcl_UniCharIsControl', 'Tcl_UniCharIsDigit', 'Tcl_UniCharIsGraph', 'Tcl_UniCharIsLower',
  836. 'Tcl_UniCharIsPrint', 'Tcl_UniCharIsPunct', 'Tcl_UniCharIsSpace', 'Tcl_UniCharIsUpper',
  837. 'Tcl_UniCharIsWordChar', 'Tcl_UniCharLen', 'Tcl_UniCharNcasecmp', 'Tcl_UniCharNcmp', 'Tcl_UniCharToLower',
  838. 'Tcl_UniCharToTitle', 'Tcl_UniCharToUpper', 'Tcl_UniCharToUtf', 'Tcl_UniCharToUtfDString', 'Tcl_UnlinkVar',
  839. 'Tcl_UnregisterChannel', 'Tcl_UnsetVar', 'Tcl_UnsetVar2', 'Tcl_UnstackChannel', 'Tcl_UntraceCommand',
  840. 'Tcl_UntraceVar', 'Tcl_UntraceVar2', 'Tcl_UpdateLinkedVar', 'Tcl_UpdateStringProc', 'Tcl_UpVar',
  841. 'Tcl_UpVar2', 'Tcl_UtfAtIndex', 'Tcl_UtfBackslash', 'Tcl_UtfCharComplete', 'Tcl_UtfFindFirst',
  842. 'Tcl_UtfFindLast', 'Tcl_UtfNext', 'Tcl_UtfPrev', 'Tcl_UtfToExternal', 'Tcl_UtfToExternalDString',
  843. 'Tcl_UtfToLower', 'Tcl_UtfToTitle', 'Tcl_UtfToUniChar', 'Tcl_UtfToUniCharDString', 'Tcl_UtfToUpper',
  844. 'Tcl_ValidateAllMemory', 'Tcl_Value', 'Tcl_VarEval', 'Tcl_VarEvalVA', 'Tcl_VarTraceInfo',
  845. 'Tcl_VarTraceInfo2', 'Tcl_VarTraceProc', 'tcl_version', 'Tcl_WaitForEvent', 'Tcl_WaitPid',
  846. 'Tcl_WinTCharToUtf', 'Tcl_WinUtfToTChar', 'tcl_wordBreakAfter', 'tcl_wordBreakBefore', 'tcl_wordchars',
  847. 'Tcl_Write', 'Tcl_WriteChars', 'Tcl_WriteObj', 'Tcl_WriteRaw', 'Tcl_WrongNumArgs', 'Tcl_ZlibAdler32',
  848. 'Tcl_ZlibCRC32', 'Tcl_ZlibDeflate', 'Tcl_ZlibInflate', 'Tcl_ZlibStreamChecksum', 'Tcl_ZlibStreamClose',
  849. 'Tcl_ZlibStreamEof', 'Tcl_ZlibStreamGet', 'Tcl_ZlibStreamGetCommandName', 'Tcl_ZlibStreamInit',
  850. 'Tcl_ZlibStreamPut', 'tcltest', 'tell', 'throw', 'time', 'tm', 'trace', 'transchan', 'try', 'unknown',
  851. 'unload', 'unset', 'update', 'uplevel', 'upvar', 'variable', 'vwait', 'while', 'yield', 'yieldto', 'zlib'
  852. ]
  853. self.autocomplete_kw_list = self.defaults['util_autocomplete_keywords'].replace(' ', '').split(',')
  854. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  855. # ###########################################################################################################
  856. # ########################################## Tools and Plugins ##############################################
  857. # ###########################################################################################################
  858. self.shell = None
  859. self.dblsidedtool = None
  860. self.distance_tool = None
  861. self.distance_min_tool = None
  862. self.panelize_tool = None
  863. self.film_tool = None
  864. self.paste_tool = None
  865. self.calculator_tool = None
  866. self.rules_tool = None
  867. self.sub_tool = None
  868. self.move_tool = None
  869. self.cutout_tool = None
  870. self.ncclear_tool = None
  871. self.paint_tool = None
  872. self.isolation_tool = None
  873. self.drilling_tool = None
  874. self.optimal_tool = None
  875. self.transform_tool = None
  876. self.properties_tool = None
  877. self.pdf_tool = None
  878. self.image_tool = None
  879. self.pcb_wizard_tool = None
  880. self.cal_exc_tool = None
  881. self.qrcode_tool = None
  882. self.copper_thieving_tool = None
  883. self.fiducial_tool = None
  884. self.edrills_tool = None
  885. self.align_objects_tool = None
  886. self.punch_tool = None
  887. self.invert_tool = None
  888. self.corners_tool = None
  889. self.etch_tool = None
  890. # always install tools only after the shell is initialized because the self.inform.emit() depends on shell
  891. try:
  892. self.install_tools()
  893. except AttributeError as e:
  894. log.debug("App.__init__() install_tools() --> %s" % str(e))
  895. # ###########################################################################################################
  896. # ######################################### BookMarks Manager ###############################################
  897. # ###########################################################################################################
  898. # install Bookmark Manager and populate bookmarks in the Help -> Bookmarks
  899. self.install_bookmarks()
  900. self.book_dialog_tab = BookmarkManager(app=self, storage=self.defaults["global_bookmarks"])
  901. # ###########################################################################################################
  902. # ########################################### Tools Database ################################################
  903. # ###########################################################################################################
  904. self.tools_db_tab = None
  905. # ### System Font Parsing ###
  906. # self.f_parse = ParseFont(self)
  907. # self.parse_system_fonts()
  908. # ###########################################################################################################
  909. # ############################################## Shell SETUP ################################################
  910. # ###########################################################################################################
  911. # show TCL shell at start-up based on the Menu -? Edit -> Preferences setting.
  912. if self.defaults["global_shell_at_startup"]:
  913. self.ui.shell_dock.show()
  914. else:
  915. self.ui.shell_dock.hide()
  916. # ###########################################################################################################
  917. # ######################################### Check for updates ###############################################
  918. # ###########################################################################################################
  919. # Separate thread (Not worker)
  920. # Check for updates on startup but only if the user consent and the app is not in Beta version
  921. if (self.beta is False or self.beta is None) and \
  922. self.ui.general_defaults_form.general_app_group.version_check_cb.get_value() is True:
  923. App.log.info("Checking for updates in backgroud (this is version %s)." % str(self.version))
  924. # self.thr2 = QtCore.QThread()
  925. self.worker_task.emit({'fcn': self.version_check,
  926. 'params': []})
  927. # self.thr2.start(QtCore.QThread.LowPriority)
  928. # ###########################################################################################################
  929. # ##################################### Register files with FlatCAM; #######################################
  930. # ################################### It works only for Windows for now ####################################
  931. # ###########################################################################################################
  932. if sys.platform == 'win32' and self.defaults["first_run"] is True:
  933. self.on_register_files()
  934. # ###########################################################################################################
  935. # ######################################## Variables for global usage #######################################
  936. # ###########################################################################################################
  937. # hold the App units
  938. self.units = 'MM'
  939. # coordinates for relative position display
  940. self.rel_point1 = (0, 0)
  941. self.rel_point2 = (0, 0)
  942. # variable to store coordinates
  943. self.pos = (0, 0)
  944. self.pos_canvas = (0, 0)
  945. self.pos_jump = (0, 0)
  946. # variable to store mouse coordinates
  947. self.mouse = [0, 0]
  948. # variable to store the delta positions on cavnas
  949. self.dx = 0
  950. self.dy = 0
  951. # decide if we have a double click or single click
  952. self.doubleclick = False
  953. # store here the is_dragging value
  954. self.event_is_dragging = False
  955. # variable to store if a command is active (then the var is not None) and which one it is
  956. self.command_active = None
  957. # variable to store the status of moving selection action
  958. # None value means that it's not an selection action
  959. # True value = a selection from left to right
  960. # False value = a selection from right to left
  961. self.selection_type = None
  962. # List to store the objects that are currently loaded in FlatCAM
  963. # This list is updated on each object creation or object delete
  964. self.all_objects_list = []
  965. self.objects_under_the_click_list = []
  966. # List to store the objects that are selected
  967. self.sel_objects_list = []
  968. # holds the key modifier if pressed (CTRL, SHIFT or ALT)
  969. self.key_modifiers = None
  970. # Variable to store the status of the code editor
  971. self.toggle_codeeditor = False
  972. # Variable to be used for situations when we don't want the LMB click on canvas to auto open the Project Tab
  973. self.click_noproject = False
  974. self.cursor = None
  975. # Variable to store the GCODE that was edited
  976. self.gcode_edited = ""
  977. # Variable to store old state of the Tools Toolbar; used in the Editor2Object and in Object2Editor methods
  978. self.old_state_of_tools_toolbar = False
  979. self.text_editor_tab = None
  980. # reference for the self.ui.code_editor
  981. self.reference_code_editor = None
  982. self.script_code = ''
  983. # if Tools DB are changed/edited in the Edit -> Tools Database tab the value will be set to True
  984. self.tools_db_changed_flag = False
  985. self.grb_list = ['art', 'bot', 'bsm', 'cmp', 'crc', 'crs', 'dim', 'g4', 'gb0', 'gb1', 'gb2', 'gb3', 'gb5',
  986. 'gb6', 'gb7', 'gb8', 'gb9', 'gbd', 'gbl', 'gbo', 'gbp', 'gbr', 'gbs', 'gdo', 'ger', 'gko',
  987. 'gml', 'gm1', 'gm2', 'gm3', 'grb', 'gtl', 'gto', 'gtp', 'gts', 'ly15', 'ly2', 'mil', 'outline',
  988. 'pho', 'plc', 'pls', 'smb', 'smt', 'sol', 'spb', 'spt', 'ssb', 'sst', 'stc', 'sts', 'top',
  989. 'tsm']
  990. self.exc_list = ['drd', 'drl', 'drill', 'exc', 'ncd', 'tap', 'txt', 'xln']
  991. self.gcode_list = ['cnc', 'din', 'dnc', 'ecs', 'eia', 'fan', 'fgc', 'fnc', 'gc', 'gcd', 'gcode', 'h', 'hnc',
  992. 'i', 'min', 'mpf', 'mpr', 'nc', 'ncc', 'ncg', 'ngc', 'ncp', 'out', 'ply', 'rol',
  993. 'sbp', 'tap', 'xpi']
  994. self.svg_list = ['svg']
  995. self.dxf_list = ['dxf']
  996. self.pdf_list = ['pdf']
  997. self.prj_list = ['flatprj']
  998. self.conf_list = ['flatconfig']
  999. # last used filters
  1000. self.last_op_gerber_filter = None
  1001. self.last_op_excellon_filter = None
  1002. self.last_op_gcode_filter = None
  1003. # global variable used by NCC Tool to signal that some polygons could not be cleared, if True
  1004. # flag for polygons not cleared
  1005. self.poly_not_cleared = False
  1006. # VisPy visuals
  1007. self.isHovering = False
  1008. self.notHovering = True
  1009. # Window geometry
  1010. self.x_pos = None
  1011. self.y_pos = None
  1012. self.width = None
  1013. self.height = None
  1014. # when True, the app has to return from any thread
  1015. self.abort_flag = False
  1016. # set the value used in the Windows Title
  1017. self.engine = self.ui.general_defaults_form.general_app_group.ge_radio.get_value()
  1018. # this holds a widget that is installed in the Plot Area when View Source option is used
  1019. self.source_editor_tab = None
  1020. self.pagesize = {}
  1021. # Storage for shapes, storage that can be used by FlatCAm tools for utility geometry
  1022. # VisPy visuals
  1023. if self.is_legacy is False:
  1024. try:
  1025. self.tool_shapes = ShapeCollection(parent=self.plotcanvas.view.scene, layers=1)
  1026. except AttributeError:
  1027. self.tool_shapes = None
  1028. else:
  1029. from appGUI.PlotCanvasLegacy import ShapeCollectionLegacy
  1030. self.tool_shapes = ShapeCollectionLegacy(obj=self, app=self, name="tool")
  1031. # used in the delayed shutdown self.start_delayed_quit() method
  1032. self.save_timer = None
  1033. # ###########################################################################################################
  1034. # ################################## ADDING FlatCAM EDITORS section #########################################
  1035. # ###########################################################################################################
  1036. # watch out for the position of the editors instantiation ... if it is done before a save of the default values
  1037. # at the first launch of the App , the editors will not be functional.
  1038. try:
  1039. self.geo_editor = AppGeoEditor(self)
  1040. except Exception as es:
  1041. log.debug("app_Main.__init__() --> Geo Editor Error: %s" % str(es))
  1042. try:
  1043. self.exc_editor = AppExcEditor(self)
  1044. except Exception as es:
  1045. log.debug("app_Main.__init__() --> Excellon Editor Error: %s" % str(es))
  1046. try:
  1047. self.grb_editor = AppGerberEditor(self)
  1048. except Exception as es:
  1049. log.debug("app_Main.__init__() --> Gerber Editor Error: %s" % str(es))
  1050. try:
  1051. self.gcode_editor = AppGCodeEditor(self)
  1052. except Exception as es:
  1053. log.debug("app_Main.__init__() --> GCode Editor Error: %s" % str(es))
  1054. self.log.debug("Finished adding FlatCAM Editor's.")
  1055. self.set_ui_title(name=_("New Project - Not saved"))
  1056. current_platform = platform.architecture()[0]
  1057. if current_platform != '64bit':
  1058. # set Excellon path optimizations algorithm to TSA if the app is run on a 32bit platform
  1059. # modes 'M' or 'B' are not allowed when the app is running in 32bit platform
  1060. if self.defaults['excellon_optimization_type'] in ['M', 'B']:
  1061. self.ui.excellon_defaults_form.excellon_gen_group.excellon_optimization_radio.set_value('T')
  1062. # set Geometry path optimizations algorithm to Rtree if the app is run on a 32bit platform
  1063. # modes 'M' or 'B' are not allowed when the app is running in 32bit platform
  1064. if self.defaults['geometry_optimization_type'] in ['M', 'B']:
  1065. self.ui.geometry_defaults_form.geometry_gen_group.opt_algorithm_radio.set_value('R')
  1066. # ###########################################################################################################
  1067. # ########################################### EXCLUSION AREAS ###############################################
  1068. # ###########################################################################################################
  1069. self.exc_areas = ExclusionAreas(app=self)
  1070. # ###########################################################################################################
  1071. # ###########################################################################################################
  1072. # ###################################### INSTANTIATE CLASSES THAT HOLD THE MENU HANDLERS ####################
  1073. # ###########################################################################################################
  1074. # ###########################################################################################################
  1075. self.f_handlers = MenuFileHandlers(app=self)
  1076. # this is calculated in the class above (somehow?)
  1077. self.defaults["root_folder_path"] = self.app_home
  1078. # ###########################################################################################################
  1079. # ############################################### SYS TRAY ##################################################
  1080. # ###########################################################################################################
  1081. if self.defaults["global_systray_icon"]:
  1082. self.parent_w = QtWidgets.QWidget()
  1083. if self.cmd_line_headless == 1:
  1084. self.trayIcon = FlatCAMSystemTray(app=self,
  1085. icon=QtGui.QIcon(self.resource_location +
  1086. '/flatcam_icon32_green.png'),
  1087. headless=True,
  1088. parent=self.parent_w)
  1089. else:
  1090. self.trayIcon = FlatCAMSystemTray(app=self,
  1091. icon=QtGui.QIcon(self.resource_location +
  1092. '/flatcam_icon32_green.png'),
  1093. parent=self.parent_w)
  1094. # ###########################################################################################################
  1095. # ############################################ SETUP RECENT ITEMS ###########################################
  1096. # ###########################################################################################################
  1097. self.setup_recent_items()
  1098. # ###########################################################################################################
  1099. # ###########################################################################################################
  1100. # ############################################# Signal handling #############################################
  1101. # ###########################################################################################################
  1102. # ###########################################################################################################
  1103. # ########################################## Custom signals ################################################
  1104. # signal for displaying messages in status bar
  1105. self.inform[str].connect(self.info)
  1106. self.inform[str, bool].connect(self.info)
  1107. # signal for displaying messages in the shell
  1108. self.inform_shell[str].connect(self.info_shell)
  1109. self.inform_shell[str, bool].connect(self.info_shell)
  1110. # signal to be called when the app is quiting
  1111. self.app_quit.connect(self.quit_application, type=Qt.QueuedConnection)
  1112. self.message.connect(lambda: message_dialog(parent=self.ui))
  1113. # self.progress.connect(self.set_progress_bar)
  1114. # signals emitted when file state change
  1115. self.file_opened.connect(self.register_recent)
  1116. self.file_opened.connect(lambda kind, filename: self.register_folder(filename))
  1117. self.file_saved.connect(lambda kind, filename: self.register_save_folder(filename))
  1118. # when the defaults dictionary values change
  1119. self.defaults.defaults.set_change_callback(callback=self.on_properties_tab_click)
  1120. # ########################################## Standard signals ###############################################
  1121. # ### Menu
  1122. self.ui.menufilenewproject.triggered.connect(self.f_handlers.on_file_new_click)
  1123. self.ui.menufilenewgeo.triggered.connect(self.app_obj.new_geometry_object)
  1124. self.ui.menufilenewgrb.triggered.connect(self.app_obj.new_gerber_object)
  1125. self.ui.menufilenewexc.triggered.connect(self.app_obj.new_excellon_object)
  1126. self.ui.menufilenewdoc.triggered.connect(self.app_obj.new_document_object)
  1127. self.ui.menufileopengerber.triggered.connect(self.f_handlers.on_fileopengerber)
  1128. self.ui.menufileopenexcellon.triggered.connect(self.f_handlers.on_fileopenexcellon)
  1129. self.ui.menufileopengcode.triggered.connect(self.f_handlers.on_fileopengcode)
  1130. self.ui.menufileopenproject.triggered.connect(self.f_handlers.on_file_openproject)
  1131. self.ui.menufileopenconfig.triggered.connect(self.f_handlers.on_file_openconfig)
  1132. self.ui.menufilenewscript.triggered.connect(self.f_handlers.on_filenewscript)
  1133. self.ui.menufileopenscript.triggered.connect(self.f_handlers.on_fileopenscript)
  1134. self.ui.menufileopenscriptexample.triggered.connect(self.f_handlers.on_fileopenscript_example)
  1135. self.ui.menufilerunscript.triggered.connect(self.f_handlers.on_filerunscript)
  1136. self.ui.menufileimportsvg.triggered.connect(lambda: self.f_handlers.on_file_importsvg("geometry"))
  1137. self.ui.menufileimportsvg_as_gerber.triggered.connect(lambda: self.f_handlers.on_file_importsvg("gerber"))
  1138. self.ui.menufileimportdxf.triggered.connect(lambda: self.f_handlers.on_file_importdxf("geometry"))
  1139. self.ui.menufileimportdxf_as_gerber.triggered.connect(lambda: self.f_handlers.on_file_importdxf("gerber"))
  1140. self.ui.menufileimport_hpgl2_as_geo.triggered.connect(self.f_handlers.on_fileopenhpgl2)
  1141. self.ui.menufileexportsvg.triggered.connect(self.f_handlers.on_file_exportsvg)
  1142. self.ui.menufileexportpng.triggered.connect(self.f_handlers.on_file_exportpng)
  1143. self.ui.menufileexportexcellon.triggered.connect(self.f_handlers.on_file_exportexcellon)
  1144. self.ui.menufileexportgerber.triggered.connect(self.f_handlers.on_file_exportgerber)
  1145. self.ui.menufileexportdxf.triggered.connect(self.f_handlers.on_file_exportdxf)
  1146. self.ui.menufile_print.triggered.connect(lambda: self.f_handlers.on_file_save_objects_pdf(use_thread=True))
  1147. self.ui.menufilesaveproject.triggered.connect(self.f_handlers.on_file_saveproject)
  1148. self.ui.menufilesaveprojectas.triggered.connect(self.f_handlers.on_file_saveprojectas)
  1149. # self.ui.menufilesaveprojectcopy.triggered.connect(lambda: self.on_file_saveprojectas(make_copy=True))
  1150. self.ui.menufilesavedefaults.triggered.connect(self.f_handlers.on_file_savedefaults)
  1151. self.ui.menufileexportpref.triggered.connect(self.f_handlers.on_export_preferences)
  1152. self.ui.menufileimportpref.triggered.connect(self.f_handlers.on_import_preferences)
  1153. self.ui.menufile_exit.triggered.connect(self.final_save)
  1154. self.ui.menueditedit.triggered.connect(lambda: self.object2editor())
  1155. self.ui.menueditok.triggered.connect(lambda: self.editor2object())
  1156. self.ui.menuedit_join2geo.triggered.connect(self.on_edit_join)
  1157. self.ui.menuedit_join_exc2exc.triggered.connect(self.on_edit_join_exc)
  1158. self.ui.menuedit_join_grb2grb.triggered.connect(self.on_edit_join_grb)
  1159. self.ui.menuedit_convert_sg2mg.triggered.connect(self.on_convert_singlegeo_to_multigeo)
  1160. self.ui.menuedit_convert_mg2sg.triggered.connect(self.on_convert_multigeo_to_singlegeo)
  1161. self.ui.menueditdelete.triggered.connect(self.on_delete)
  1162. self.ui.menueditcopyobject.triggered.connect(self.on_copy_command)
  1163. self.ui.menueditconvert_any2geo.triggered.connect(self.convert_any2geo)
  1164. self.ui.menueditconvert_any2gerber.triggered.connect(self.convert_any2gerber)
  1165. self.ui.menueditconvert_any2excellon.triggered.connect(self.convert_any2excellon)
  1166. self.ui.menueditorigin.triggered.connect(self.on_set_origin)
  1167. self.ui.menuedit_move2origin.triggered.connect(self.on_move2origin)
  1168. self.ui.menueditjump.triggered.connect(self.on_jump_to)
  1169. self.ui.menueditlocate.triggered.connect(lambda: self.on_locate(obj=self.collection.get_active()))
  1170. self.ui.menuedittoggleunits.triggered.connect(self.on_toggle_units_click)
  1171. self.ui.menueditselectall.triggered.connect(self.on_selectall)
  1172. self.ui.menueditpreferences.triggered.connect(self.on_preferences)
  1173. # self.ui.menuoptions_transfer_a2o.triggered.connect(self.on_options_app2object)
  1174. # self.ui.menuoptions_transfer_a2p.triggered.connect(self.on_options_app2project)
  1175. # self.ui.menuoptions_transfer_o2a.triggered.connect(self.on_options_object2app)
  1176. # self.ui.menuoptions_transfer_p2a.triggered.connect(self.on_options_project2app)
  1177. # self.ui.menuoptions_transfer_o2p.triggered.connect(self.on_options_object2project)
  1178. # self.ui.menuoptions_transfer_p2o.triggered.connect(self.on_options_project2object)
  1179. self.ui.menuoptions_transform_rotate.triggered.connect(self.on_rotate)
  1180. self.ui.menuoptions_transform_skewx.triggered.connect(self.on_skewx)
  1181. self.ui.menuoptions_transform_skewy.triggered.connect(self.on_skewy)
  1182. self.ui.menuoptions_transform_flipx.triggered.connect(self.on_flipx)
  1183. self.ui.menuoptions_transform_flipy.triggered.connect(self.on_flipy)
  1184. self.ui.menuoptions_view_source.triggered.connect(self.on_view_source)
  1185. self.ui.menuoptions_tools_db.triggered.connect(lambda: self.on_tools_database(source='app'))
  1186. self.ui.menuviewdisableall.triggered.connect(self.disable_all_plots)
  1187. self.ui.menuviewdisableother.triggered.connect(self.disable_other_plots)
  1188. self.ui.menuviewenable.triggered.connect(self.enable_all_plots)
  1189. self.ui.menuview_zoom_fit.triggered.connect(self.on_zoom_fit)
  1190. self.ui.menuview_zoom_in.triggered.connect(self.on_zoom_in)
  1191. self.ui.menuview_zoom_out.triggered.connect(self.on_zoom_out)
  1192. self.ui.menuview_replot.triggered.connect(self.plot_all)
  1193. self.ui.menuview_toggle_code_editor.triggered.connect(self.on_toggle_code_editor)
  1194. self.ui.menuview_toggle_fscreen.triggered.connect(self.ui.on_fullscreen)
  1195. self.ui.menuview_toggle_parea.triggered.connect(self.ui.on_toggle_plotarea)
  1196. self.ui.menuview_toggle_notebook.triggered.connect(self.ui.on_toggle_notebook)
  1197. self.ui.menu_toggle_nb.triggered.connect(self.ui.on_toggle_notebook)
  1198. self.ui.menuview_toggle_grid.triggered.connect(self.ui.on_toggle_grid)
  1199. self.ui.menuview_toggle_workspace.triggered.connect(self.on_workspace_toggle)
  1200. self.ui.menuview_toggle_grid_lines.triggered.connect(self.plotcanvas.on_toggle_grid_lines)
  1201. self.ui.menuview_toggle_axis.triggered.connect(self.plotcanvas.on_toggle_axis)
  1202. self.ui.menuview_toggle_hud.triggered.connect(self.plotcanvas.on_toggle_hud)
  1203. self.ui.menutoolshell.triggered.connect(self.ui.toggle_shell_ui)
  1204. self.ui.menuhelp_about.triggered.connect(self.on_about)
  1205. self.ui.menuhelp_readme.triggered.connect(self.on_readme)
  1206. self.ui.menuhelp_manual.triggered.connect(lambda: webbrowser.open(self.manual_url))
  1207. self.ui.menuhelp_report_bug.triggered.connect(lambda: webbrowser.open(self.bug_report_url))
  1208. self.ui.menuhelp_exc_spec.triggered.connect(lambda: webbrowser.open(self.excellon_spec_url))
  1209. self.ui.menuhelp_gerber_spec.triggered.connect(lambda: webbrowser.open(self.gerber_spec_url))
  1210. self.ui.menuhelp_videohelp.triggered.connect(lambda: webbrowser.open(self.video_url))
  1211. self.ui.menuhelp_shortcut_list.triggered.connect(self.on_shortcut_list)
  1212. self.ui.menuprojectenable.triggered.connect(self.on_enable_sel_plots)
  1213. self.ui.menuprojectdisable.triggered.connect(self.on_disable_sel_plots)
  1214. self.ui.menuprojectgeneratecnc.triggered.connect(lambda: self.generate_cnc_job(self.collection.get_selected()))
  1215. self.ui.menuprojectviewsource.triggered.connect(self.on_view_source)
  1216. self.ui.menuprojectcopy.triggered.connect(self.on_copy_command)
  1217. self.ui.menuprojectedit.triggered.connect(self.object2editor)
  1218. self.ui.menuprojectdelete.triggered.connect(self.on_delete)
  1219. self.ui.menuprojectsave.triggered.connect(self.on_project_context_save)
  1220. self.ui.menuprojectproperties.triggered.connect(self.obj_properties)
  1221. # ToolBar signals
  1222. self.connect_toolbar_signals(ui=self.ui)
  1223. # Context Menu
  1224. self.ui.popmenu_disable.triggered.connect(lambda: self.toggle_plots(self.collection.get_selected()))
  1225. self.ui.popmenu_panel_toggle.triggered.connect(self.ui.on_toggle_notebook)
  1226. self.ui.popmenu_new_geo.triggered.connect(self.app_obj.new_geometry_object)
  1227. self.ui.popmenu_new_grb.triggered.connect(self.app_obj.new_gerber_object)
  1228. self.ui.popmenu_new_exc.triggered.connect(self.app_obj.new_excellon_object)
  1229. self.ui.popmenu_new_prj.triggered.connect(self.f_handlers.on_file_new)
  1230. self.ui.zoomfit.triggered.connect(self.on_zoom_fit)
  1231. self.ui.clearplot.triggered.connect(self.clear_plots)
  1232. self.ui.replot.triggered.connect(self.plot_all)
  1233. self.ui.popmenu_copy.triggered.connect(self.on_copy_command)
  1234. self.ui.popmenu_delete.triggered.connect(self.on_delete)
  1235. self.ui.popmenu_edit.triggered.connect(self.object2editor)
  1236. self.ui.popmenu_save.triggered.connect(lambda: self.editor2object())
  1237. self.ui.popmenu_move.triggered.connect(self.obj_move)
  1238. self.ui.popmenu_properties.triggered.connect(self.obj_properties)
  1239. # Project Context Menu -> Color Setting
  1240. for act in self.ui.menuprojectcolor.actions():
  1241. act.triggered.connect(self.on_set_color_action_triggered)
  1242. # Notebook tab clicking
  1243. self.ui.notebook.tabBarClicked.connect(self.on_properties_tab_click)
  1244. # ###########################################################################################################
  1245. # #################################### GUI PREFERENCES SIGNALS ##############################################
  1246. # ###########################################################################################################
  1247. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.connect(
  1248. lambda: self.on_toggle_units(no_pref=False))
  1249. # ##################################### Workspace Setting Signals ###########################################
  1250. self.ui.general_defaults_form.general_app_set_group.wk_cb.currentIndexChanged.connect(
  1251. self.on_workspace_modified)
  1252. self.ui.general_defaults_form.general_app_set_group.wk_orientation_radio.activated_custom.connect(
  1253. self.on_workspace_modified
  1254. )
  1255. self.ui.general_defaults_form.general_app_set_group.workspace_cb.stateChanged.connect(self.on_workspace)
  1256. # ###########################################################################################################
  1257. # ######################################## GUI SETTINGS SIGNALS #############################################
  1258. # ###########################################################################################################
  1259. self.ui.general_defaults_form.general_app_set_group.cursor_radio.activated_custom.connect(self.on_cursor_type)
  1260. # ######################################## Tools related signals ############################################
  1261. # portability changed signal
  1262. self.ui.general_defaults_form.general_app_group.portability_cb.stateChanged.connect(self.on_portable_checked)
  1263. # Object list
  1264. self.object_status_changed.connect(self.collection.on_collection_updated)
  1265. # when there are arguments at application startup this get launched
  1266. self.args_at_startup[list].connect(self.on_startup_args)
  1267. # ###########################################################################################################
  1268. # ####################################### FILE ASSOCIATIONS SIGNALS #########################################
  1269. # ###########################################################################################################
  1270. self.ui.util_defaults_form.fa_excellon_group.restore_btn.clicked.connect(
  1271. lambda: self.restore_extensions(ext_type='excellon'))
  1272. self.ui.util_defaults_form.fa_gcode_group.restore_btn.clicked.connect(
  1273. lambda: self.restore_extensions(ext_type='gcode'))
  1274. self.ui.util_defaults_form.fa_gerber_group.restore_btn.clicked.connect(
  1275. lambda: self.restore_extensions(ext_type='gerber'))
  1276. self.ui.util_defaults_form.fa_excellon_group.del_all_btn.clicked.connect(
  1277. lambda: self.delete_all_extensions(ext_type='excellon'))
  1278. self.ui.util_defaults_form.fa_gcode_group.del_all_btn.clicked.connect(
  1279. lambda: self.delete_all_extensions(ext_type='gcode'))
  1280. self.ui.util_defaults_form.fa_gerber_group.del_all_btn.clicked.connect(
  1281. lambda: self.delete_all_extensions(ext_type='gerber'))
  1282. self.ui.util_defaults_form.fa_excellon_group.add_btn.clicked.connect(
  1283. lambda: self.add_extension(ext_type='excellon'))
  1284. self.ui.util_defaults_form.fa_gcode_group.add_btn.clicked.connect(
  1285. lambda: self.add_extension(ext_type='gcode'))
  1286. self.ui.util_defaults_form.fa_gerber_group.add_btn.clicked.connect(
  1287. lambda: self.add_extension(ext_type='gerber'))
  1288. self.ui.util_defaults_form.fa_excellon_group.del_btn.clicked.connect(
  1289. lambda: self.del_extension(ext_type='excellon'))
  1290. self.ui.util_defaults_form.fa_gcode_group.del_btn.clicked.connect(
  1291. lambda: self.del_extension(ext_type='gcode'))
  1292. self.ui.util_defaults_form.fa_gerber_group.del_btn.clicked.connect(
  1293. lambda: self.del_extension(ext_type='gerber'))
  1294. # connect the 'Apply' buttons from the Preferences/File Associations
  1295. self.ui.util_defaults_form.fa_excellon_group.exc_list_btn.clicked.connect(
  1296. lambda: self.on_register_files(obj_type='excellon'))
  1297. self.ui.util_defaults_form.fa_gcode_group.gco_list_btn.clicked.connect(
  1298. lambda: self.on_register_files(obj_type='gcode'))
  1299. self.ui.util_defaults_form.fa_gerber_group.grb_list_btn.clicked.connect(
  1300. lambda: self.on_register_files(obj_type='gerber'))
  1301. # ###########################################################################################################
  1302. # ########################################### KEYWORDS SIGNALS ##############################################
  1303. # ###########################################################################################################
  1304. self.ui.util_defaults_form.kw_group.restore_btn.clicked.connect(
  1305. lambda: self.restore_extensions(ext_type='keyword'))
  1306. self.ui.util_defaults_form.kw_group.del_all_btn.clicked.connect(
  1307. lambda: self.delete_all_extensions(ext_type='keyword'))
  1308. self.ui.util_defaults_form.kw_group.add_btn.clicked.connect(
  1309. lambda: self.add_extension(ext_type='keyword'))
  1310. self.ui.util_defaults_form.kw_group.del_btn.clicked.connect(
  1311. lambda: self.del_extension(ext_type='keyword'))
  1312. # ###########################################################################################################
  1313. # ########################################### GUI SIGNALS ###################################################
  1314. # ###########################################################################################################
  1315. self.ui.hud_label.clicked.connect(self.plotcanvas.on_toggle_hud)
  1316. self.ui.axis_status_label.clicked.connect(self.plotcanvas.on_toggle_axis)
  1317. self.ui.pref_status_label.clicked.connect(self.on_toggle_preferences)
  1318. # ###########################################################################################################
  1319. # ####################################### VARIOUS SIGNALS ###################################################
  1320. # ###########################################################################################################
  1321. # connect the abort_all_tasks related slots to the related signals
  1322. self.proc_container.idle_flag.connect(self.app_is_idle)
  1323. # signal emitted when a tab is closed in the Plot Area
  1324. self.ui.plot_tab_area.tab_closed_signal.connect(self.on_plot_area_tab_closed)
  1325. # signal to close the application
  1326. self.close_app_signal.connect(self.kill_app)
  1327. # ################################# FINISHED CONNECTING SIGNALS #############################################
  1328. # ###########################################################################################################
  1329. # ###########################################################################################################
  1330. # ###########################################################################################################
  1331. self.log.debug("Finished connecting Signals.")
  1332. # ###########################################################################################################
  1333. # ##################################### Finished the CONSTRUCTOR ############################################
  1334. # ###########################################################################################################
  1335. App.log.debug("END of constructor. Releasing control.")
  1336. # ###########################################################################################################
  1337. # ########################################## SHOW GUI #######################################################
  1338. # ###########################################################################################################
  1339. # if the app is not started as headless, show it
  1340. if self.cmd_line_headless != 1:
  1341. if show_splash:
  1342. # finish the splash
  1343. self.splash.finish(self.ui)
  1344. mgui_settings = QSettings("Open Source", "FlatCAM")
  1345. if mgui_settings.contains("maximized_gui"):
  1346. maximized_ui = mgui_settings.value('maximized_gui', type=bool)
  1347. if maximized_ui is True:
  1348. self.ui.showMaximized()
  1349. else:
  1350. self.ui.show()
  1351. else:
  1352. self.ui.show()
  1353. if self.defaults["global_systray_icon"]:
  1354. self.trayIcon.show()
  1355. else:
  1356. log.warning("******************* RUNNING HEADLESS *******************")
  1357. # ###########################################################################################################
  1358. # ######################################## START-UP ARGUMENTS ###############################################
  1359. # ###########################################################################################################
  1360. # test if the program was started with a script as parameter
  1361. if self.cmd_line_shellvar:
  1362. try:
  1363. cnt = 0
  1364. command_tcl = 0
  1365. for i in self.cmd_line_shellvar.split(','):
  1366. if i is not None:
  1367. # noinspection PyBroadException
  1368. try:
  1369. command_tcl = eval(i)
  1370. except Exception:
  1371. command_tcl = i
  1372. command_tcl_formatted = 'set shellvar_{nr} "{cmd}"'.format(cmd=str(command_tcl), nr=str(cnt))
  1373. cnt += 1
  1374. # if there are Windows paths then replace the path separator with a Unix like one
  1375. if sys.platform == 'win32':
  1376. command_tcl_formatted = command_tcl_formatted.replace('\\', '/')
  1377. self.shell.exec_command(command_tcl_formatted, no_echo=True)
  1378. except Exception as ext:
  1379. print("ERROR: ", ext)
  1380. sys.exit(2)
  1381. if self.cmd_line_shellfile:
  1382. if self.cmd_line_headless != 1:
  1383. if self.ui.shell_dock.isHidden():
  1384. self.ui.shell_dock.show()
  1385. try:
  1386. with open(self.cmd_line_shellfile, "r") as myfile:
  1387. # if show_splash:
  1388. # self.splash.showMessage('%s: %ssec\n%s' % (
  1389. # _("Canvas initialization started.\n"
  1390. # "Canvas initialization finished in"), '%.2f' % self.used_time,
  1391. # _("Executing Tcl Script ...")),
  1392. # alignment=Qt.AlignBottom | Qt.AlignLeft,
  1393. # color=QtGui.QColor("gray"))
  1394. cmd_line_shellfile_text = myfile.read()
  1395. if self.cmd_line_headless != 1:
  1396. self.shell.exec_command(cmd_line_shellfile_text)
  1397. else:
  1398. self.shell.exec_command(cmd_line_shellfile_text, no_echo=True)
  1399. except Exception as ext:
  1400. print("ERROR: ", ext)
  1401. sys.exit(2)
  1402. # accept some type file as command line parameter: FlatCAM project, FlatCAM preferences or scripts
  1403. # the path/file_name must be enclosed in quotes if it contain spaces
  1404. if App.args:
  1405. self.args_at_startup.emit(App.args)
  1406. if self.defaults.old_defaults_found is True:
  1407. self.inform.emit('[WARNING_NOTCL] %s' % _("Found old default preferences files. "
  1408. "Please reboot the application to update."))
  1409. self.defaults.old_defaults_found = False
  1410. # ######################################### INIT FINISHED #######################################################
  1411. # #################################################################################################################
  1412. # #################################################################################################################
  1413. # #################################################################################################################
  1414. # #################################################################################################################
  1415. # #################################################################################################################
  1416. @staticmethod
  1417. def copy_and_overwrite(from_path, to_path):
  1418. """
  1419. From here:
  1420. https://stackoverflow.com/questions/12683834/how-to-copy-directory-recursively-in-python-and-overwrite-all
  1421. :param from_path: source path
  1422. :param to_path: destination path
  1423. :return: None
  1424. """
  1425. if os.path.exists(to_path):
  1426. shutil.rmtree(to_path)
  1427. try:
  1428. shutil.copytree(from_path, to_path)
  1429. except FileNotFoundError:
  1430. from_new_path = os.path.dirname(os.path.realpath(__file__)) + '\\appGUI\\VisPyData\\data'
  1431. shutil.copytree(from_new_path, to_path)
  1432. def on_startup_args(self, args, silent=False):
  1433. """
  1434. This will process any arguments provided to the application at startup. Like trying to launch a file or project.
  1435. :param silent: when True it will not print messages on Tcl Shell and/or status bar
  1436. :param args: a list containing the application args at startup
  1437. :return: None
  1438. """
  1439. if args is not None:
  1440. args_to_process = args
  1441. else:
  1442. args_to_process = App.args
  1443. log.debug("Application was started with arguments: %s. Processing ..." % str(args_to_process))
  1444. for argument in args_to_process:
  1445. if '.FlatPrj'.lower() in argument.lower():
  1446. try:
  1447. project_name = str(argument)
  1448. if project_name == "":
  1449. if silent is False:
  1450. self.inform.emit(_("Cancelled."))
  1451. else:
  1452. # self.open_project(project_name)
  1453. run_from_arg = True
  1454. # self.worker_task.emit({'fcn': self.open_project,
  1455. # 'params': [project_name, run_from_arg]})
  1456. self.open_project(filename=project_name, run_from_arg=run_from_arg)
  1457. except Exception as e:
  1458. log.debug("Could not open FlatCAM project file as App parameter due: %s" % str(e))
  1459. elif '.FlatConfig'.lower() in argument.lower():
  1460. try:
  1461. file_name = str(argument)
  1462. if file_name == "":
  1463. if silent is False:
  1464. self.inform.emit(_("Open Config file failed."))
  1465. else:
  1466. run_from_arg = True
  1467. # self.worker_task.emit({'fcn': self.open_config_file,
  1468. # 'params': [file_name, run_from_arg]})
  1469. self.open_config_file(file_name, run_from_arg=run_from_arg)
  1470. except Exception as e:
  1471. log.debug("Could not open FlatCAM Config file as App parameter due: %s" % str(e))
  1472. elif '.FlatScript'.lower() in argument.lower() or '.TCL'.lower() in argument.lower():
  1473. try:
  1474. file_name = str(argument)
  1475. if file_name == "":
  1476. if silent is False:
  1477. self.inform.emit(_("Open Script file failed."))
  1478. else:
  1479. if silent is False:
  1480. self.on_fileopenscript(name=file_name)
  1481. self.ui.plot_tab_area.setCurrentWidget(self.ui.plot_tab)
  1482. self.on_filerunscript(name=file_name)
  1483. except Exception as e:
  1484. log.debug("Could not open FlatCAM Script file as App parameter due: %s" % str(e))
  1485. elif 'quit'.lower() in argument.lower() or 'exit'.lower() in argument.lower():
  1486. log.debug("App.on_startup_args() --> Quit event.")
  1487. sys.exit()
  1488. elif 'save'.lower() in argument.lower():
  1489. log.debug("App.on_startup_args() --> Save event. App Defaults saved.")
  1490. self.preferencesUiManager.save_defaults()
  1491. else:
  1492. exc_list = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().split(',')
  1493. proc_arg = argument.lower()
  1494. for ext in exc_list:
  1495. proc_ext = ext.replace(' ', '')
  1496. proc_ext = '.%s' % proc_ext
  1497. if proc_ext.lower() in proc_arg and proc_ext != '.':
  1498. file_name = str(argument)
  1499. if file_name == "":
  1500. if silent is False:
  1501. self.inform.emit(_("Open Excellon file failed."))
  1502. else:
  1503. self.on_fileopenexcellon(name=file_name, signal=None)
  1504. return
  1505. gco_list = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().split(',')
  1506. for ext in gco_list:
  1507. proc_ext = ext.replace(' ', '')
  1508. proc_ext = '.%s' % proc_ext
  1509. if proc_ext.lower() in proc_arg and proc_ext != '.':
  1510. file_name = str(argument)
  1511. if file_name == "":
  1512. if silent is False:
  1513. self.inform.emit(_("Open GCode file failed."))
  1514. else:
  1515. self.on_fileopengcode(name=file_name, signal=None)
  1516. return
  1517. grb_list = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().split(',')
  1518. for ext in grb_list:
  1519. proc_ext = ext.replace(' ', '')
  1520. proc_ext = '.%s' % proc_ext
  1521. if proc_ext.lower() in proc_arg and proc_ext != '.':
  1522. file_name = str(argument)
  1523. if file_name == "":
  1524. if silent is False:
  1525. self.inform.emit(_("Open Gerber file failed."))
  1526. else:
  1527. self.on_fileopengerber(name=file_name, signal=None)
  1528. return
  1529. # if it reached here without already returning then the app was registered with a file that it does not
  1530. # recognize therefore we must quit but take into consideration the app reboot from within, in that case
  1531. # the args_to_process will contain the path to the FlatCAM.exe (cx_freezed executable)
  1532. # for arg in args_to_process:
  1533. # if 'FlatCAM.exe' in arg:
  1534. # continue
  1535. # else:
  1536. # sys.exit(2)
  1537. def set_ui_title(self, name):
  1538. """
  1539. Sets the title of the main window.
  1540. :param name: String that store the project path and project name
  1541. :return: None
  1542. """
  1543. self.ui.setWindowTitle('FlatCAM %s %s - %s - [%s] %s' %
  1544. (self.version,
  1545. ('BETA' if self.beta else ''),
  1546. platform.architecture()[0],
  1547. self.engine,
  1548. name)
  1549. )
  1550. def on_app_restart(self):
  1551. # make sure that the Sys Tray icon is hidden before restart otherwise it will
  1552. # be left in the SySTray
  1553. try:
  1554. self.trayIcon.hide()
  1555. except Exception:
  1556. pass
  1557. fcTranslate.restart_program(app=self)
  1558. def clear_pool(self):
  1559. """
  1560. Clear the multiprocessing pool and calls garbage collector.
  1561. :return: None
  1562. """
  1563. self.pool.close()
  1564. self.pool = Pool()
  1565. self.pool_recreated.emit(self.pool)
  1566. gc.collect()
  1567. def install_tools(self):
  1568. """
  1569. This installs the FlatCAM tools (plugin-like) which reside in their own classes.
  1570. Instantiation of the Tools classes.
  1571. The order that the tools are installed is important as they can depend on each other install position.
  1572. :return: None
  1573. """
  1574. # shell tool has t obe initialized always first because other tools print messages in the Shell Dock
  1575. self.shell = FCShell(app=self, version=self.version)
  1576. self.distance_tool = Distance(self)
  1577. self.distance_tool.install(icon=QtGui.QIcon(self.resource_location + '/distance16.png'), pos=self.ui.menuedit,
  1578. before=self.ui.menueditorigin,
  1579. separator=False)
  1580. self.distance_min_tool = DistanceMin(self)
  1581. self.distance_min_tool.install(icon=QtGui.QIcon(self.resource_location + '/distance_min16.png'),
  1582. pos=self.ui.menuedit,
  1583. before=self.ui.menueditorigin,
  1584. separator=True)
  1585. self.dblsidedtool = DblSidedTool(self)
  1586. self.dblsidedtool.install(icon=QtGui.QIcon(self.resource_location + '/doubleside16.png'), separator=False)
  1587. self.cal_exc_tool = ToolCalibration(self)
  1588. self.cal_exc_tool.install(icon=QtGui.QIcon(self.resource_location + '/calibrate_16.png'), pos=self.ui.menutool,
  1589. before=self.dblsidedtool.menuAction,
  1590. separator=False)
  1591. self.align_objects_tool = AlignObjects(self)
  1592. self.align_objects_tool.install(icon=QtGui.QIcon(self.resource_location + '/align16.png'), separator=False)
  1593. self.edrills_tool = ToolExtractDrills(self)
  1594. self.edrills_tool.install(icon=QtGui.QIcon(self.resource_location + '/drill16.png'), separator=True)
  1595. self.panelize_tool = Panelize(self)
  1596. self.panelize_tool.install(icon=QtGui.QIcon(self.resource_location + '/panelize16.png'))
  1597. self.film_tool = Film(self)
  1598. self.film_tool.install(icon=QtGui.QIcon(self.resource_location + '/film16.png'))
  1599. self.paste_tool = SolderPaste(self)
  1600. self.paste_tool.install(icon=QtGui.QIcon(self.resource_location + '/solderpastebis32.png'))
  1601. self.calculator_tool = ToolCalculator(self)
  1602. self.calculator_tool.install(icon=QtGui.QIcon(self.resource_location + '/calculator16.png'), separator=True)
  1603. self.sub_tool = ToolSub(self)
  1604. self.sub_tool.install(icon=QtGui.QIcon(self.resource_location + '/sub32.png'),
  1605. pos=self.ui.menutool, separator=True)
  1606. self.rules_tool = RulesCheck(self)
  1607. self.rules_tool.install(icon=QtGui.QIcon(self.resource_location + '/rules32.png'),
  1608. pos=self.ui.menutool, separator=False)
  1609. self.optimal_tool = ToolOptimal(self)
  1610. self.optimal_tool.install(icon=QtGui.QIcon(self.resource_location + '/open_excellon32.png'),
  1611. pos=self.ui.menutool, separator=True)
  1612. self.move_tool = ToolMove(self)
  1613. self.move_tool.install(icon=QtGui.QIcon(self.resource_location + '/move16.png'), pos=self.ui.menuedit,
  1614. before=self.ui.menueditorigin, separator=True)
  1615. self.cutout_tool = CutOut(self)
  1616. self.cutout_tool.install(icon=QtGui.QIcon(self.resource_location + '/cut16_bis.png'), pos=self.ui.menutool,
  1617. before=self.sub_tool.menuAction)
  1618. self.ncclear_tool = NonCopperClear(self)
  1619. self.ncclear_tool.install(icon=QtGui.QIcon(self.resource_location + '/ncc16.png'), pos=self.ui.menutool,
  1620. before=self.sub_tool.menuAction, separator=True)
  1621. self.paint_tool = ToolPaint(self)
  1622. self.paint_tool.install(icon=QtGui.QIcon(self.resource_location + '/paint16.png'), pos=self.ui.menutool,
  1623. before=self.sub_tool.menuAction, separator=True)
  1624. self.isolation_tool = ToolIsolation(self)
  1625. self.isolation_tool.install(icon=QtGui.QIcon(self.resource_location + '/iso_16.png'), pos=self.ui.menutool,
  1626. before=self.sub_tool.menuAction, separator=True)
  1627. self.drilling_tool = ToolDrilling(self)
  1628. self.drilling_tool.install(icon=QtGui.QIcon(self.resource_location + '/drill16.png'), pos=self.ui.menutool,
  1629. before=self.sub_tool.menuAction, separator=True)
  1630. self.copper_thieving_tool = ToolCopperThieving(self)
  1631. self.copper_thieving_tool.install(icon=QtGui.QIcon(self.resource_location + '/copperfill32.png'),
  1632. pos=self.ui.menutool)
  1633. self.fiducial_tool = ToolFiducials(self)
  1634. self.fiducial_tool.install(icon=QtGui.QIcon(self.resource_location + '/fiducials_32.png'),
  1635. pos=self.ui.menutool)
  1636. self.qrcode_tool = QRCode(self)
  1637. self.qrcode_tool.install(icon=QtGui.QIcon(self.resource_location + '/qrcode32.png'),
  1638. pos=self.ui.menutool)
  1639. self.punch_tool = ToolPunchGerber(self)
  1640. self.punch_tool.install(icon=QtGui.QIcon(self.resource_location + '/punch32.png'), pos=self.ui.menutool)
  1641. self.invert_tool = ToolInvertGerber(self)
  1642. self.invert_tool.install(icon=QtGui.QIcon(self.resource_location + '/invert32.png'), pos=self.ui.menutool)
  1643. self.corners_tool = ToolCorners(self)
  1644. self.corners_tool.install(icon=QtGui.QIcon(self.resource_location + '/corners_32.png'), pos=self.ui.menutool)
  1645. self.etch_tool = ToolEtchCompensation(self)
  1646. self.etch_tool.install(icon=QtGui.QIcon(self.resource_location + '/etch_32.png'), pos=self.ui.menutool)
  1647. self.transform_tool = ToolTransform(self)
  1648. self.transform_tool.install(icon=QtGui.QIcon(self.resource_location + '/transform.png'),
  1649. pos=self.ui.menuoptions, separator=True)
  1650. self.properties_tool = Properties(self)
  1651. self.properties_tool.install(icon=QtGui.QIcon(self.resource_location + '/properties32.png'),
  1652. pos=self.ui.menuoptions)
  1653. self.pdf_tool = ToolPDF(self)
  1654. self.pdf_tool.install(icon=QtGui.QIcon(self.resource_location + '/pdf32.png'),
  1655. pos=self.ui.menufileimport,
  1656. separator=True)
  1657. self.image_tool = ToolImage(self)
  1658. self.image_tool.install(icon=QtGui.QIcon(self.resource_location + '/image32.png'),
  1659. pos=self.ui.menufileimport,
  1660. separator=True)
  1661. self.pcb_wizard_tool = PcbWizard(self)
  1662. self.pcb_wizard_tool.install(icon=QtGui.QIcon(self.resource_location + '/drill32.png'),
  1663. pos=self.ui.menufileimport)
  1664. self.log.debug("Tools are installed.")
  1665. def remove_tools(self):
  1666. """
  1667. Will remove all the actions in the Tool menu.
  1668. :return: None
  1669. """
  1670. for act in self.ui.menutool.actions():
  1671. self.ui.menutool.removeAction(act)
  1672. def init_tools(self):
  1673. """
  1674. Initialize the Tool tab in the notebook side of the central widget.
  1675. Remove the actions in the Tools menu.
  1676. Instantiate again the FlatCAM tools (plugins).
  1677. All this is required when changing the layout: standard, compact etc.
  1678. :return: None
  1679. """
  1680. log.debug("init_tools()")
  1681. # delete the data currently in the Tools Tab and the Tab itself
  1682. widget = QtWidgets.QTabWidget.widget(self.ui.notebook, 2)
  1683. if widget is not None:
  1684. widget.deleteLater()
  1685. self.ui.notebook.removeTab(2)
  1686. # rebuild the Tools Tab
  1687. self.ui.tool_tab = QtWidgets.QWidget()
  1688. self.ui.tool_tab_layout = QtWidgets.QVBoxLayout(self.ui.tool_tab)
  1689. self.ui.tool_tab_layout.setContentsMargins(2, 2, 2, 2)
  1690. self.ui.notebook.addTab(self.ui.tool_tab, _("Tool"))
  1691. self.ui.tool_scroll_area = VerticalScrollArea()
  1692. self.ui.tool_tab_layout.addWidget(self.ui.tool_scroll_area)
  1693. # reinstall all the Tools as some may have been removed when the data was removed from the Tools Tab
  1694. # first remove all of them
  1695. self.remove_tools()
  1696. # re-add the TCL Shell action to the Tools menu and reconnect it to ist slot function
  1697. self.ui.menutoolshell = self.ui.menutool.addAction(QtGui.QIcon(self.resource_location + '/shell16.png'),
  1698. '&Command Line\tS')
  1699. self.ui.menutoolshell.triggered.connect(self.ui.toggle_shell_ui)
  1700. # third install all of them
  1701. try:
  1702. self.install_tools()
  1703. except AttributeError:
  1704. pass
  1705. self.log.debug("Tools are initialized.")
  1706. # def parse_system_fonts(self):
  1707. # self.worker_task.emit({'fcn': self.f_parse.get_fonts_by_types,
  1708. # 'params': []})
  1709. def connect_tools_signals_to_toolbar(self, ui):
  1710. ui.dblsided_btn.triggered.connect(lambda: self.dblsidedtool.run(toggle=True))
  1711. ui.cal_btn.triggered.connect(lambda: self.cal_exc_tool.run(toggle=True))
  1712. ui.align_btn.triggered.connect(lambda: self.align_objects_tool.run(toggle=True))
  1713. ui.extract_btn.triggered.connect(lambda: self.edrills_tool.run(toggle=True))
  1714. ui.cutout_btn.triggered.connect(lambda: self.cutout_tool.run(toggle=True))
  1715. ui.ncc_btn.triggered.connect(lambda: self.ncclear_tool.run(toggle=True))
  1716. ui.paint_btn.triggered.connect(lambda: self.paint_tool.run(toggle=True))
  1717. ui.isolation_btn.triggered.connect(lambda: self.isolation_tool.run(toggle=True))
  1718. ui.drill_btn.triggered.connect(lambda: self.drilling_tool.run(toggle=True))
  1719. ui.panelize_btn.triggered.connect(lambda: self.panelize_tool.run(toggle=True))
  1720. ui.film_btn.triggered.connect(lambda: self.film_tool.run(toggle=True))
  1721. ui.solder_btn.triggered.connect(lambda: self.paste_tool.run(toggle=True))
  1722. ui.sub_btn.triggered.connect(lambda: self.sub_tool.run(toggle=True))
  1723. ui.rules_btn.triggered.connect(lambda: self.rules_tool.run(toggle=True))
  1724. ui.optimal_btn.triggered.connect(lambda: self.optimal_tool.run(toggle=True))
  1725. ui.calculators_btn.triggered.connect(lambda: self.calculator_tool.run(toggle=True))
  1726. ui.transform_btn.triggered.connect(lambda: self.transform_tool.run(toggle=True))
  1727. ui.qrcode_btn.triggered.connect(lambda: self.qrcode_tool.run(toggle=True))
  1728. ui.copperfill_btn.triggered.connect(lambda: self.copper_thieving_tool.run(toggle=True))
  1729. ui.fiducials_btn.triggered.connect(lambda: self.fiducial_tool.run(toggle=True))
  1730. ui.punch_btn.triggered.connect(lambda: self.punch_tool.run(toggle=True))
  1731. ui.invert_btn.triggered.connect(lambda: self.invert_tool.run(toggle=True))
  1732. ui.corners_tool_btn.triggered.connect(lambda: self.corners_tool.run(toggle=True))
  1733. ui.etch_btn.triggered.connect(lambda: self.etch_tool.run(toggle=True))
  1734. def connect_toolbar_signals(self, ui):
  1735. """
  1736. Reconnect the signals to the actions in the toolbar.
  1737. This has to be done each time after the FlatCAM tools are removed/installed.
  1738. :return: None
  1739. """
  1740. # Toolbar
  1741. # File Toolbar Signals
  1742. # ui.file_new_btn.triggered.connect(self.on_file_new)
  1743. ui.file_open_btn.triggered.connect(self.f_handlers.on_file_openproject)
  1744. ui.file_save_btn.triggered.connect(self.f_handlers.on_file_saveproject)
  1745. ui.file_open_gerber_btn.triggered.connect(self.f_handlers.on_fileopengerber)
  1746. ui.file_open_excellon_btn.triggered.connect(self.f_handlers.on_fileopenexcellon)
  1747. # View Toolbar Signals
  1748. ui.clear_plot_btn.triggered.connect(self.clear_plots)
  1749. ui.replot_btn.triggered.connect(self.plot_all)
  1750. ui.zoom_fit_btn.triggered.connect(self.on_zoom_fit)
  1751. ui.zoom_in_btn.triggered.connect(lambda: self.plotcanvas.zoom(1 / 1.5))
  1752. ui.zoom_out_btn.triggered.connect(lambda: self.plotcanvas.zoom(1.5))
  1753. # Edit Toolbar Signals
  1754. ui.editgeo_btn.triggered.connect(self.object2editor)
  1755. ui.update_obj_btn.triggered.connect(lambda: self.editor2object())
  1756. ui.copy_btn.triggered.connect(self.on_copy_command)
  1757. ui.delete_btn.triggered.connect(self.on_delete)
  1758. ui.distance_btn.triggered.connect(lambda: self.distance_tool.run(toggle=True))
  1759. ui.distance_min_btn.triggered.connect(lambda: self.distance_min_tool.run(toggle=True))
  1760. ui.origin_btn.triggered.connect(self.on_set_origin)
  1761. ui.move2origin_btn.triggered.connect(self.on_move2origin)
  1762. ui.jmp_btn.triggered.connect(self.on_jump_to)
  1763. ui.locate_btn.triggered.connect(lambda: self.on_locate(obj=self.collection.get_active()))
  1764. # Scripting Toolbar Signals
  1765. ui.shell_btn.triggered.connect(ui.toggle_shell_ui)
  1766. ui.new_script_btn.triggered.connect(self.f_handlers.on_filenewscript)
  1767. ui.open_script_btn.triggered.connect(self.f_handlers.on_fileopenscript)
  1768. ui.run_script_btn.triggered.connect(self.f_handlers.on_filerunscript)
  1769. # Tools Toolbar Signals
  1770. try:
  1771. self.connect_tools_signals_to_toolbar(ui=ui)
  1772. except Exception as err:
  1773. log.debug("App.connect_toolbar_signals() tools signals -> %s" % str(err))
  1774. def object2editor(self):
  1775. """
  1776. Send the current Geometry, Gerber, Excellon object or CNCJob (if any) into the it's editor.
  1777. :return: None
  1778. """
  1779. self.defaults.report_usage("object2editor()")
  1780. # disable the objects menu as it may interfere with the appEditors
  1781. self.ui.menuobjects.setDisabled(True)
  1782. edited_object = self.collection.get_active()
  1783. if isinstance(edited_object, GerberObject) or isinstance(edited_object, GeometryObject) or \
  1784. isinstance(edited_object, ExcellonObject) or isinstance(edited_object, CNCJobObject):
  1785. pass
  1786. else:
  1787. self.inform.emit('[WARNING_NOTCL] %s' % _("Select a Geometry, Gerber, Excellon or CNCJob Object to edit."))
  1788. return
  1789. if isinstance(edited_object, GeometryObject):
  1790. # store the Geometry Editor Toolbar visibility before entering in the Editor
  1791. self.geo_editor.toolbar_old_state = True if self.ui.geo_edit_toolbar.isVisible() else False
  1792. # we set the notebook to hidden
  1793. # self.ui.splitter.setSizes([0, 1])
  1794. if edited_object.multigeo is True:
  1795. sel_rows = [item.row() for item in edited_object.ui.geo_tools_table.selectedItems()]
  1796. if len(sel_rows) > 1:
  1797. self.inform.emit('[WARNING_NOTCL] %s' %
  1798. _("Simultaneous editing of tools geometry in a MultiGeo Geometry "
  1799. "is not possible.\n"
  1800. "Edit only one geometry at a time."))
  1801. if not sel_rows:
  1802. self.inform.emit('[WARNING_NOTCL] %s.' % _("No Tool Selected"))
  1803. return
  1804. # determine the tool dia of the selected tool
  1805. selected_tooldia = float(edited_object.ui.geo_tools_table.item(sel_rows[0], 1).text())
  1806. # now find the key in the edited_object.tools that has this tooldia
  1807. multi_tool = 1
  1808. for tool in edited_object.tools:
  1809. if edited_object.tools[tool]['tooldia'] == selected_tooldia:
  1810. multi_tool = tool
  1811. break
  1812. log.debug("Editing MultiGeo Geometry with tool diameter: %s" % str(multi_tool))
  1813. self.geo_editor.edit_fcgeometry(edited_object, multigeo_tool=multi_tool)
  1814. else:
  1815. log.debug("Editing SingleGeo Geometry with tool diameter.")
  1816. self.geo_editor.edit_fcgeometry(edited_object)
  1817. # set call source to the Editor we go into
  1818. self.call_source = 'geo_editor'
  1819. elif isinstance(edited_object, ExcellonObject):
  1820. # store the Excellon Editor Toolbar visibility before entering in the Editor
  1821. self.exc_editor.toolbar_old_state = True if self.ui.exc_edit_toolbar.isVisible() else False
  1822. if self.ui.splitter.sizes()[0] == 0:
  1823. self.ui.splitter.setSizes([1, 1])
  1824. self.exc_editor.edit_fcexcellon(edited_object)
  1825. # set call source to the Editor we go into
  1826. self.call_source = 'exc_editor'
  1827. elif isinstance(edited_object, GerberObject):
  1828. # store the Gerber Editor Toolbar visibility before entering in the Editor
  1829. self.grb_editor.toolbar_old_state = True if self.ui.grb_edit_toolbar.isVisible() else False
  1830. if self.ui.splitter.sizes()[0] == 0:
  1831. self.ui.splitter.setSizes([1, 1])
  1832. self.grb_editor.edit_fcgerber(edited_object)
  1833. # set call source to the Editor we go into
  1834. self.call_source = 'grb_editor'
  1835. # reset the following variables so the UI is built again after edit
  1836. edited_object.ui_build = False
  1837. elif isinstance(edited_object, CNCJobObject):
  1838. if self.ui.splitter.sizes()[0] == 0:
  1839. self.ui.splitter.setSizes([1, 1])
  1840. # set call source to the Editor we go into
  1841. self.call_source = 'gcode_editor'
  1842. self.gcode_editor.edit_fcgcode(edited_object)
  1843. # make sure that we can't select another object while in Editor Mode:
  1844. # self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.NoSelection)
  1845. self.ui.project_frame.setDisabled(True)
  1846. # delete any selection shape that might be active as they are not relevant in Editor
  1847. self.delete_selection_shape()
  1848. # hide the Tools Toolbar
  1849. tools_tb = self.ui.toolbartools
  1850. if tools_tb.isVisible():
  1851. self.old_state_of_tools_toolbar = True
  1852. tools_tb.hide()
  1853. else:
  1854. self.old_state_of_tools_toolbar = False
  1855. self.ui.plot_tab_area.setTabText(0, _("EDITOR Area"))
  1856. self.ui.plot_tab_area.protectTab(0)
  1857. self.inform.emit('[WARNING_NOTCL] %s' % _("Editor is activated ..."))
  1858. self.should_we_save = True
  1859. def editor2object(self, cleanup=None):
  1860. """
  1861. Transfers the Geometry or Excellon from it's editor to the current object.
  1862. :return: None
  1863. """
  1864. self.defaults.report_usage("editor2object()")
  1865. # re-enable the objects menu that was disabled on entry in Editor mode
  1866. self.ui.menuobjects.setDisabled(False)
  1867. # do not update a geometry or excellon object unless it comes out of an editor
  1868. if self.call_source != 'app':
  1869. edited_obj = self.collection.get_active()
  1870. if cleanup is None:
  1871. msgbox = QtWidgets.QMessageBox()
  1872. msgbox.setText(_("Do you want to save the edited object?"))
  1873. msgbox.setWindowTitle(_("Close Editor"))
  1874. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  1875. msgbox.setIcon(QtWidgets.QMessageBox.Question)
  1876. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  1877. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  1878. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  1879. msgbox.setDefaultButton(bt_yes)
  1880. msgbox.exec_()
  1881. response = msgbox.clickedButton()
  1882. if response == bt_yes:
  1883. # show the Tools Toolbar
  1884. tools_tb = self.ui.toolbartools
  1885. if self.old_state_of_tools_toolbar is True:
  1886. tools_tb.show()
  1887. # clean the Tools Tab
  1888. self.ui.tool_scroll_area.takeWidget()
  1889. self.ui.tool_scroll_area.setWidget(QtWidgets.QWidget())
  1890. self.ui.notebook.setTabText(2, _("Tool"))
  1891. if edited_obj.kind == 'geometry':
  1892. obj_type = "Geometry"
  1893. self.geo_editor.update_fcgeometry(edited_obj)
  1894. # self.geo_editor.update_options(edited_obj)
  1895. # restore GUI to the Selected TAB
  1896. # Remove anything else in the appGUI
  1897. self.ui.tool_scroll_area.takeWidget()
  1898. # update the geo object options so it is including the bounding box values
  1899. try:
  1900. xmin, ymin, xmax, ymax = edited_obj.bounds(flatten=True)
  1901. edited_obj.options['xmin'] = xmin
  1902. edited_obj.options['ymin'] = ymin
  1903. edited_obj.options['xmax'] = xmax
  1904. edited_obj.options['ymax'] = ymax
  1905. except AttributeError as e:
  1906. self.inform.emit('[WARNING] %s' % _("Object empty after edit."))
  1907. log.debug("App.editor2object() --> Geometry --> %s" % str(e))
  1908. edited_obj.build_ui()
  1909. edited_obj.plot()
  1910. self.inform.emit('[success] %s' % _("Editor exited. Editor content saved."))
  1911. elif edited_obj.kind == 'gerber':
  1912. obj_type = "Gerber"
  1913. self.grb_editor.update_fcgerber()
  1914. # self.grb_editor.update_options(edited_obj)
  1915. # delete the old object (the source object) if it was an empty one
  1916. try:
  1917. if len(edited_obj.solid_geometry) == 0:
  1918. old_name = edited_obj.options['name']
  1919. self.collection.delete_by_name(old_name)
  1920. except TypeError:
  1921. # if the solid_geometry is a single Polygon the len() will not work
  1922. # in any case, falling here means that we have something in the solid_geometry, even if only
  1923. # a single Polygon, therefore we pass this
  1924. pass
  1925. self.inform.emit('[success] %s' % _("Editor exited. Editor content saved."))
  1926. # restore GUI to the Selected TAB
  1927. # Remove anything else in the GUI
  1928. self.ui.properties_scroll_area.takeWidget()
  1929. elif edited_obj.kind == 'excellon':
  1930. obj_type = "Excellon"
  1931. self.exc_editor.update_fcexcellon(edited_obj)
  1932. # self.exc_editor.update_options(edited_obj)
  1933. # restore GUI to the Selected TAB
  1934. # Remove anything else in the GUI
  1935. self.ui.tool_scroll_area.takeWidget()
  1936. # delete the old object (the source object) if it was an empty one
  1937. # find if we have drills:
  1938. has_drills = None
  1939. for tt in edited_obj.tools:
  1940. if 'drills' in edited_obj.tools[tt] and edited_obj.tools[tt]['drills']:
  1941. has_drills = True
  1942. break
  1943. # find if we have slots:
  1944. has_slots = None
  1945. for tt in edited_obj.tools:
  1946. if 'slots' in edited_obj.tools[tt] and edited_obj.tools[tt]['slots']:
  1947. has_slots = True
  1948. break
  1949. if has_drills is None and has_slots is None:
  1950. old_name = edited_obj.options['name']
  1951. self.collection.delete_by_name(name=old_name)
  1952. self.inform.emit('[success] %s' % _("Editor exited. Editor content saved."))
  1953. elif edited_obj.kind == 'cncjob':
  1954. obj_type = "CNCJob"
  1955. self.gcode_editor.update_fcgcode(edited_obj)
  1956. # self.exc_editor.update_options(edited_obj)
  1957. # restore GUI to the Selected TAB
  1958. # Remove anything else in the GUI
  1959. self.ui.tool_scroll_area.takeWidget()
  1960. edited_obj.build_ui()
  1961. # close the open tab
  1962. for idx in range(self.ui.plot_tab_area.count()):
  1963. if self.ui.plot_tab_area.widget(idx).objectName() == 'gcode_editor_tab':
  1964. self.ui.plot_tab_area.closeTab(idx)
  1965. self.inform.emit('[success] %s' % _("Editor exited. Editor content saved."))
  1966. else:
  1967. self.inform.emit('[WARNING_NOTCL] %s' %
  1968. _("Select a Gerber, Geometry, Excellon or CNCJob Object to update."))
  1969. return
  1970. self.inform.emit('[selected] %s %s' % (obj_type, _("is updated, returning to App...")))
  1971. elif response == bt_no:
  1972. # show the Tools Toolbar
  1973. tools_tb = self.ui.toolbartools
  1974. if self.old_state_of_tools_toolbar is True:
  1975. tools_tb.show()
  1976. # clean the Tools Tab
  1977. self.ui.tool_scroll_area.takeWidget()
  1978. self.ui.tool_scroll_area.setWidget(QtWidgets.QWidget())
  1979. self.ui.notebook.setTabText(2, _("Tool"))
  1980. self.inform.emit('[WARNING_NOTCL] %s' % _("Editor exited. Editor content was not saved."))
  1981. if edited_obj.kind == 'geometry':
  1982. self.geo_editor.deactivate()
  1983. edited_obj.build_ui()
  1984. edited_obj.plot()
  1985. elif edited_obj.kind == 'gerber':
  1986. self.grb_editor.deactivate_grb_editor()
  1987. edited_obj.build_ui()
  1988. elif edited_obj.kind == 'excellon':
  1989. self.exc_editor.deactivate()
  1990. edited_obj.build_ui()
  1991. elif edited_obj.kind == 'cncjob':
  1992. self.gcode_editor.deactivate()
  1993. edited_obj.build_ui()
  1994. # close the open tab
  1995. for idx in range(self.ui.plot_tab_area.count()):
  1996. try:
  1997. if self.ui.plot_tab_area.widget(idx).objectName() == 'gcode_editor_tab':
  1998. self.ui.plot_tab_area.closeTab(idx)
  1999. except AttributeError:
  2000. continue
  2001. else:
  2002. self.inform.emit('[WARNING_NOTCL] %s' %
  2003. _("Select a Gerber, Geometry, Excellon or CNCJob Object to update."))
  2004. return
  2005. elif response == bt_cancel:
  2006. return
  2007. # edited_obj.set_ui(edited_obj.ui_type(decimals=self.decimals))
  2008. # edited_obj.build_ui()
  2009. # Switch notebook to Properties page
  2010. # self.ui.notebook.setCurrentWidget(self.ui.properties_tab)
  2011. else:
  2012. # show the Tools Toolbar
  2013. tools_tb = self.ui.toolbartools
  2014. if self.old_state_of_tools_toolbar is True:
  2015. tools_tb.show()
  2016. if isinstance(edited_obj, GeometryObject):
  2017. self.geo_editor.deactivate()
  2018. elif isinstance(edited_obj, GerberObject):
  2019. self.grb_editor.deactivate_grb_editor()
  2020. elif isinstance(edited_obj, ExcellonObject):
  2021. self.exc_editor.deactivate()
  2022. else:
  2023. self.inform.emit('[WARNING_NOTCL] %s' %
  2024. _("Select a Gerber, Geometry or Excellon Object to update."))
  2025. return
  2026. # if notebook is hidden we show it
  2027. if self.ui.splitter.sizes()[0] == 0:
  2028. self.ui.splitter.setSizes([1, 1])
  2029. # restore the call_source to app
  2030. self.call_source = 'app'
  2031. # edited_obj.plot()
  2032. self.ui.plot_tab_area.setTabText(0, _("Plot Area"))
  2033. self.ui.plot_tab_area.protectTab(0)
  2034. # make sure that we reenable the selection on Project Tab after returning from Editor Mode:
  2035. # self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection)
  2036. self.ui.project_frame.setDisabled(False)
  2037. def get_last_folder(self):
  2038. """
  2039. Get the folder path from where the last file was opened.
  2040. :return: String, last opened folder path
  2041. """
  2042. return self.defaults["global_last_folder"]
  2043. def get_last_save_folder(self):
  2044. """
  2045. Get the folder path from where the last file was saved.
  2046. :return: String, last saved folder path
  2047. """
  2048. loc = self.defaults["global_last_save_folder"]
  2049. if loc is None:
  2050. loc = self.defaults["global_last_folder"]
  2051. if loc is None:
  2052. loc = os.path.dirname(__file__)
  2053. return loc
  2054. @QtCore.pyqtSlot(str)
  2055. @QtCore.pyqtSlot(str, bool)
  2056. def info(self, msg, shell_echo=True):
  2057. """
  2058. Informs the user. Normally on the status bar, optionally
  2059. also on the shell.
  2060. :param msg: Text to write.
  2061. :type msg: str
  2062. :param shell_echo: Control if to display the message msg in the Shell
  2063. :type shell_echo: bool
  2064. :return: None
  2065. """
  2066. # Type of message in brackets at the beginning of the message.
  2067. match = re.search(r"\[(.*)\](.*)", msg)
  2068. if match:
  2069. level = match.group(1)
  2070. msg_ = match.group(2)
  2071. self.ui.fcinfo.set_status(str(msg_), level=level)
  2072. if shell_echo is True:
  2073. if level.lower() == "error":
  2074. self.shell_message(msg, error=True, show=True)
  2075. elif level.lower() == "warning":
  2076. self.shell_message(msg, warning=True, show=True)
  2077. elif level.lower() == "error_notcl":
  2078. self.shell_message(msg, error=True, show=False)
  2079. elif level.lower() == "warning_notcl":
  2080. self.shell_message(msg, warning=True, show=False)
  2081. elif level.lower() == "success":
  2082. self.shell_message(msg, success=True, show=False)
  2083. elif level.lower() == "selected":
  2084. self.shell_message(msg, selected=True, show=False)
  2085. else:
  2086. self.shell_message(msg, show=False)
  2087. else:
  2088. self.ui.fcinfo.set_status(str(msg), level="info")
  2089. # make sure that if the message is to clear the infobar with a space
  2090. # is not printed over and over on the shell
  2091. if msg != '' and shell_echo is True:
  2092. self.shell_message(msg)
  2093. def info_shell(self, msg, new_line=True):
  2094. self.shell_message(msg=msg, new_line=new_line)
  2095. def save_to_file(self, content_to_save, txt_content):
  2096. """
  2097. Save something to a file.
  2098. :return: None
  2099. """
  2100. self.defaults.report_usage("save_to_file")
  2101. App.log.debug("save_to_file()")
  2102. self.date = str(datetime.today()).rpartition('.')[0]
  2103. self.date = ''.join(c for c in self.date if c not in ':-')
  2104. self.date = self.date.replace(' ', '_')
  2105. filter__ = "HTML File .html (*.html);;TXT File .txt (*.txt);;All Files (*.*)"
  2106. path_to_save = self.defaults["global_last_save_folder"] if \
  2107. self.defaults["global_last_save_folder"] is not None else self.data_path
  2108. try:
  2109. filename, _f = FCFileSaveDialog.get_saved_filename(
  2110. caption=_("Save to file"),
  2111. directory=path_to_save + '/file_' + self.date,
  2112. ext_filter=filter__
  2113. )
  2114. except TypeError:
  2115. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save to file"), ext_filter=filter__)
  2116. filename = str(filename)
  2117. if filename == "":
  2118. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  2119. return
  2120. else:
  2121. try:
  2122. with open(filename, 'w') as f:
  2123. ___ = f.read()
  2124. except PermissionError:
  2125. self.inform.emit('[WARNING] %s' %
  2126. _("Permission denied, saving not possible.\n"
  2127. "Most likely another app is holding the file open and not accessible."))
  2128. return
  2129. except IOError:
  2130. App.log.debug('Creating a new file ...')
  2131. f = open(filename, 'w')
  2132. f.close()
  2133. except Exception:
  2134. e = sys.exc_info()[0]
  2135. App.log.error("Could not load the file.")
  2136. App.log.error(str(e))
  2137. self.inform.emit('[ERROR_NOTCL] %s' % _("Could not load the file."))
  2138. return
  2139. # Save content
  2140. if filename.rpartition('.')[2].lower() == 'html':
  2141. file_content = content_to_save
  2142. else:
  2143. file_content = txt_content
  2144. try:
  2145. with open(filename, "w") as f:
  2146. f.write(file_content)
  2147. except Exception:
  2148. self.inform.emit('[ERROR_NOTCL] %s %s' % (_("Failed to write defaults to file."), str(filename)))
  2149. return
  2150. self.inform.emit('[success] %s: %s' % (_("Exported file to"), filename))
  2151. def register_recent(self, kind, filename):
  2152. """
  2153. Will register the files opened into record dictionaries. The FlatCAM projects has it's own
  2154. dictionary.
  2155. :param kind: type of file that was opened
  2156. :param filename: the path and file name for the file that was opened
  2157. :return:
  2158. """
  2159. self.log.debug("register_recent()")
  2160. self.log.debug(" %s" % kind)
  2161. self.log.debug(" %s" % filename)
  2162. record = {'kind': str(kind), 'filename': str(filename)}
  2163. if record in self.recent:
  2164. return
  2165. if record in self.recent_projects:
  2166. return
  2167. if record['kind'] == 'project':
  2168. self.recent_projects.insert(0, record)
  2169. else:
  2170. self.recent.insert(0, record)
  2171. if len(self.recent) > self.defaults['global_recent_limit']: # Limit reached
  2172. self.recent.pop()
  2173. if len(self.recent_projects) > self.defaults['global_recent_limit']: # Limit reached
  2174. self.recent_projects.pop()
  2175. try:
  2176. f = open(self.data_path + '/recent.json', 'w')
  2177. except IOError:
  2178. App.log.error("Failed to open recent items file for writing.")
  2179. self.inform.emit('[ERROR_NOTCL] %s' %
  2180. _('Failed to open recent files file for writing.'))
  2181. return
  2182. json.dump(self.recent, f, default=to_dict, indent=2, sort_keys=True)
  2183. f.close()
  2184. try:
  2185. fp = open(self.data_path + '/recent_projects.json', 'w')
  2186. except IOError:
  2187. App.log.error("Failed to open recent items file for writing.")
  2188. self.inform.emit('[ERROR_NOTCL] %s' %
  2189. _('Failed to open recent projects file for writing.'))
  2190. return
  2191. json.dump(self.recent_projects, fp, default=to_dict, indent=2, sort_keys=True)
  2192. fp.close()
  2193. # Re-build the recent items menu
  2194. self.setup_recent_items()
  2195. def on_about(self):
  2196. """
  2197. Displays the "about" dialog found in the Menu --> Help.
  2198. :return: None
  2199. """
  2200. self.defaults.report_usage("on_about")
  2201. version = self.version
  2202. version_date = self.version_date
  2203. beta = self.beta
  2204. class AboutDialog(QtWidgets.QDialog):
  2205. def __init__(self, app, parent=None):
  2206. QtWidgets.QDialog.__init__(self, parent)
  2207. self.app = app
  2208. # Icon and title
  2209. self.setWindowIcon(parent.app_icon)
  2210. self.setWindowTitle(_("About FlatCAM"))
  2211. self.resize(600, 200)
  2212. # self.setStyleSheet("background-image: url(share/flatcam_icon256.png); background-attachment: fixed")
  2213. # self.setStyleSheet(
  2214. # "border-image: url(share/flatcam_icon256.png) 0 0 0 0 stretch stretch; "
  2215. # "background-attachment: fixed"
  2216. # )
  2217. # bgimage = QtGui.QImage(self.resource_location + '/flatcam_icon256.png')
  2218. # s_bgimage = bgimage.scaled(QtCore.QSize(self.frameGeometry().width(), self.frameGeometry().height()))
  2219. # palette = QtGui.QPalette()
  2220. # palette.setBrush(10, QtGui.QBrush(bgimage)) # 10 = Windowrole
  2221. # self.setPalette(palette)
  2222. logo = QtWidgets.QLabel()
  2223. logo.setPixmap(QtGui.QPixmap(self.app.resource_location + '/flatcam_icon256.png'))
  2224. title = QtWidgets.QLabel(
  2225. "<font size=8><B>FlatCAM</B></font><BR>"
  2226. "{title}<BR>"
  2227. "<BR>"
  2228. "<BR>"
  2229. "<a href = \"https://bitbucket.org/jpcgt/flatcam/src/Beta/\"><B>{devel}</B></a><BR>"
  2230. "<a href = \"https://bitbucket.org/jpcgt/flatcam/downloads/\"><b>{down}</B></a><BR>"
  2231. "<a href = \"https://bitbucket.org/jpcgt/flatcam/issues?status=new&status=open/\">"
  2232. "<B>{issue}</B></a><BR>".format(
  2233. title=_("2D Computer-Aided Printed Circuit Board Manufacturing"),
  2234. devel=_("Development"),
  2235. down=_("DOWNLOAD"),
  2236. issue=_("Issue tracker"))
  2237. )
  2238. title.setOpenExternalLinks(True)
  2239. closebtn = QtWidgets.QPushButton(_("Close"))
  2240. tab_widget = QtWidgets.QTabWidget()
  2241. description_label = QtWidgets.QLabel(
  2242. "FlatCAM {version} {beta} ({date}) - {arch}<br>"
  2243. "<a href = \"http://flatcam.org/\">http://flatcam.org</a><br>".format(
  2244. version=version,
  2245. beta=('BETA' if beta else ''),
  2246. date=version_date,
  2247. arch=platform.architecture()[0])
  2248. )
  2249. description_label.setOpenExternalLinks(True)
  2250. lic_lbl_header = QtWidgets.QLabel(
  2251. '%s:<br>%s<br>' % (
  2252. _('Licensed under the MIT license'),
  2253. "<a href = \"http://www.opensource.org/licenses/mit-license.php\">"
  2254. "http://www.opensource.org/licenses/mit-license.php</a>"
  2255. )
  2256. )
  2257. lic_lbl_header.setOpenExternalLinks(True)
  2258. lic_lbl_body = QtWidgets.QLabel(
  2259. _(
  2260. 'Permission is hereby granted, free of charge, to any person obtaining a copy\n'
  2261. 'of this software and associated documentation files (the "Software"), to deal\n'
  2262. 'in the Software without restriction, including without limitation the rights\n'
  2263. 'to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n'
  2264. 'copies of the Software, and to permit persons to whom the Software is\n'
  2265. 'furnished to do so, subject to the following conditions:\n\n'
  2266. 'The above copyright notice and this permission notice shall be included in\n'
  2267. 'all copies or substantial portions of the Software.\n\n'
  2268. 'THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n'
  2269. 'IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n'
  2270. 'FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n'
  2271. 'AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n'
  2272. 'LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n'
  2273. 'OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n'
  2274. 'THE SOFTWARE.'
  2275. )
  2276. )
  2277. attributions_label = QtWidgets.QLabel(
  2278. _(
  2279. 'Some of the icons used are from the following sources:<br>'
  2280. '<div>Icons by <a href="https://www.flaticon.com/authors/freepik" '
  2281. 'title="Freepik">Freepik</a> from <a href="https://www.flaticon.com/" '
  2282. 'title="Flaticon">www.flaticon.com</a></div>'
  2283. '<div>Icons by <a target="_blank" href="https://icons8.com">Icons8</a></div>'
  2284. 'Icons by <a href="http://www.onlinewebfonts.com">oNline Web Fonts</a>'
  2285. '<div>Icons by <a href="https://www.flaticon.com/authors/pixel-perfect" '
  2286. 'title="Pixel perfect">Pixel perfect</a> from <a href="https://www.flaticon.com/" '
  2287. 'title="Flaticon">www.flaticon.com</a></div>'
  2288. )
  2289. )
  2290. attributions_label.setOpenExternalLinks(True)
  2291. # layouts
  2292. layout1 = QtWidgets.QVBoxLayout()
  2293. layout1_1 = QtWidgets.QHBoxLayout()
  2294. layout1_2 = QtWidgets.QHBoxLayout()
  2295. layout2 = QtWidgets.QHBoxLayout()
  2296. layout3 = QtWidgets.QHBoxLayout()
  2297. self.setLayout(layout1)
  2298. layout1.addLayout(layout1_1)
  2299. layout1.addLayout(layout1_2)
  2300. layout1.addLayout(layout2)
  2301. layout1.addLayout(layout3)
  2302. layout1_1.addStretch()
  2303. layout1_1.addWidget(description_label)
  2304. layout1_2.addWidget(tab_widget)
  2305. self.splash_tab = QtWidgets.QWidget()
  2306. self.splash_tab.setObjectName("splash_about")
  2307. self.splash_tab_layout = QtWidgets.QHBoxLayout(self.splash_tab)
  2308. self.splash_tab_layout.setContentsMargins(2, 2, 2, 2)
  2309. tab_widget.addTab(self.splash_tab, _("Splash"))
  2310. self.programmmers_tab = QtWidgets.QWidget()
  2311. self.programmmers_tab.setObjectName("programmers_about")
  2312. self.programmmers_tab_layout = QtWidgets.QVBoxLayout(self.programmmers_tab)
  2313. self.programmmers_tab_layout.setContentsMargins(2, 2, 2, 2)
  2314. tab_widget.addTab(self.programmmers_tab, _("Programmers"))
  2315. self.translators_tab = QtWidgets.QWidget()
  2316. self.translators_tab.setObjectName("translators_about")
  2317. self.translators_tab_layout = QtWidgets.QVBoxLayout(self.translators_tab)
  2318. self.translators_tab_layout.setContentsMargins(2, 2, 2, 2)
  2319. tab_widget.addTab(self.translators_tab, _("Translators"))
  2320. self.license_tab = QtWidgets.QWidget()
  2321. self.license_tab.setObjectName("license_about")
  2322. self.license_tab_layout = QtWidgets.QVBoxLayout(self.license_tab)
  2323. self.license_tab_layout.setContentsMargins(2, 2, 2, 2)
  2324. tab_widget.addTab(self.license_tab, _("License"))
  2325. self.attributions_tab = QtWidgets.QWidget()
  2326. self.attributions_tab.setObjectName("attributions_about")
  2327. self.attributions_tab_layout = QtWidgets.QVBoxLayout(self.attributions_tab)
  2328. self.attributions_tab_layout.setContentsMargins(2, 2, 2, 2)
  2329. tab_widget.addTab(self.attributions_tab, _("Attributions"))
  2330. self.splash_tab_layout.addWidget(logo, stretch=0)
  2331. self.splash_tab_layout.addWidget(title, stretch=1)
  2332. pal = QtGui.QPalette()
  2333. pal.setColor(QtGui.QPalette.Background, Qt.white)
  2334. self.prog_grid_lay = QtWidgets.QGridLayout()
  2335. self.prog_grid_lay.setHorizontalSpacing(20)
  2336. self.prog_grid_lay.setColumnStretch(0, 0)
  2337. self.prog_grid_lay.setColumnStretch(2, 1)
  2338. prog_widget = QtWidgets.QWidget()
  2339. prog_widget.setLayout(self.prog_grid_lay)
  2340. prog_scroll = QtWidgets.QScrollArea()
  2341. prog_scroll.setWidget(prog_widget)
  2342. prog_scroll.setWidgetResizable(True)
  2343. prog_scroll.setFrameShape(QtWidgets.QFrame.NoFrame)
  2344. prog_scroll.setPalette(pal)
  2345. self.programmmers_tab_layout.addWidget(prog_scroll)
  2346. self.prog_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Programmer")), 0, 0)
  2347. self.prog_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Status")), 0, 1)
  2348. self.prog_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("E-mail")), 0, 2)
  2349. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Juan Pablo Caram"), 1, 0)
  2350. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % _("Program Author")), 1, 1)
  2351. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<>"), 1, 2)
  2352. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Denis Hayrullin"), 2, 0)
  2353. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Kamil Sopko"), 3, 0)
  2354. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu"), 4, 0)
  2355. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % _("BETA Maintainer >= 2019")), 4, 1)
  2356. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<marius_adrian@yahoo.com>"), 4, 2)
  2357. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 5, 0)
  2358. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "David Robertson"), 6, 0)
  2359. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Matthieu Berthomé"), 7, 0)
  2360. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Mike Evans"), 8, 0)
  2361. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Victor Benso"), 9, 0)
  2362. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 10, 0)
  2363. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Jørn Sandvik Nilsson"), 12, 0)
  2364. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Lei Zheng"), 13, 0)
  2365. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Leandro Heck"), 14, 0)
  2366. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marco A Quezada"), 15, 0)
  2367. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 16, 0)
  2368. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Cedric Dussud"), 20, 0)
  2369. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Chris Hemingway"), 22, 0)
  2370. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Damian Wrobel"), 24, 0)
  2371. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Daniel Sallin"), 28, 0)
  2372. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 32, 0)
  2373. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Bruno Vunderl"), 40, 0)
  2374. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Gonzalo Lopez"), 42, 0)
  2375. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Jakob Staudt"), 45, 0)
  2376. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Mike Smith"), 49, 0)
  2377. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 52, 0)
  2378. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Barnaby Walters"), 55, 0)
  2379. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Steve Martina"), 57, 0)
  2380. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Thomas Duffin"), 59, 0)
  2381. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Andrey Kultyapov"), 61, 0)
  2382. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 63, 0)
  2383. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Alex Lazar"), 64, 0)
  2384. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Chris Breneman"), 65, 0)
  2385. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Eric Varsanyi"), 67, 0)
  2386. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Lubos Medovarsky"), 69, 0)
  2387. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 74, 0)
  2388. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@Idechix"), 100, 0)
  2389. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@SM"), 101, 0)
  2390. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@grbf"), 102, 0)
  2391. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@Symonty"), 103, 0)
  2392. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@mgix"), 104, 0)
  2393. self.translator_grid_lay = QtWidgets.QGridLayout()
  2394. self.translator_grid_lay.setColumnStretch(0, 0)
  2395. self.translator_grid_lay.setColumnStretch(1, 0)
  2396. self.translator_grid_lay.setColumnStretch(2, 1)
  2397. self.translator_grid_lay.setColumnStretch(3, 0)
  2398. # trans_widget = QtWidgets.QWidget()
  2399. # trans_widget.setLayout(self.translator_grid_lay)
  2400. # self.translators_tab_layout.addWidget(trans_widget)
  2401. # self.translators_tab_layout.addStretch()
  2402. trans_widget = QtWidgets.QWidget()
  2403. trans_widget.setLayout(self.translator_grid_lay)
  2404. trans_scroll = QtWidgets.QScrollArea()
  2405. trans_scroll.setWidget(trans_widget)
  2406. trans_scroll.setWidgetResizable(True)
  2407. trans_scroll.setFrameShape(QtWidgets.QFrame.NoFrame)
  2408. trans_scroll.setPalette(pal)
  2409. self.translators_tab_layout.addWidget(trans_scroll)
  2410. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Language")), 0, 0)
  2411. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Translator")), 0, 1)
  2412. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Corrections")), 0, 2)
  2413. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("E-mail")), 0, 3)
  2414. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "BR - Portuguese"), 1, 0)
  2415. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Carlos Stein"), 1, 1)
  2416. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<carlos.stein@gmail.com>"), 1, 3)
  2417. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "French"), 2, 0)
  2418. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Michel Maciejewski"), 2, 1)
  2419. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % ""), 2, 2)
  2420. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<micmac589@gmail.com>"), 2, 3)
  2421. # self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Hungarian"), 3, 0)
  2422. # self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 3, 1)
  2423. # self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 3, 2)
  2424. # self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 3, 3)
  2425. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Italian"), 4, 0)
  2426. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Massimiliano Golfetto"), 4, 1)
  2427. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 4, 2)
  2428. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<golfetto.pcb@gmail.com>"), 4, 3)
  2429. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "German"), 5, 0)
  2430. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu (Google-Tr)"), 5, 1)
  2431. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Jens Karstedt, Detlef Eckardt"), 5, 2)
  2432. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 5, 3)
  2433. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Romanian"), 6, 0)
  2434. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu"), 6, 1)
  2435. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<marius_adrian@yahoo.com>"), 6, 3)
  2436. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Russian"), 7, 0)
  2437. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Andrey Kultyapov"), 7, 1)
  2438. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<camellan@yandex.ru>"), 7, 3)
  2439. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Spanish"), 8, 0)
  2440. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu (Google-Tr)"), 8, 1)
  2441. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % ""), 8, 2)
  2442. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 8, 3)
  2443. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Turkish"), 9, 0)
  2444. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Mehmet Kaya"), 9, 1)
  2445. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<malatyakaya480@gmail.com>"), 9, 3)
  2446. self.translator_grid_lay.setColumnStretch(0, 0)
  2447. self.translators_tab_layout.addStretch()
  2448. self.license_tab_layout.addWidget(lic_lbl_header)
  2449. self.license_tab_layout.addWidget(lic_lbl_body)
  2450. self.license_tab_layout.addStretch()
  2451. self.attributions_tab_layout.addWidget(attributions_label)
  2452. self.attributions_tab_layout.addStretch()
  2453. layout3.addStretch()
  2454. layout3.addWidget(closebtn)
  2455. closebtn.clicked.connect(self.accept)
  2456. AboutDialog(app=self, parent=self.ui).exec_()
  2457. def on_readme(self):
  2458. """
  2459. Displays the "about" dialog found in the Menu --> Help.
  2460. :return: None
  2461. """
  2462. class ReadmeDialog(QtWidgets.QDialog):
  2463. def __init__(self, app, parent=None):
  2464. QtWidgets.QDialog.__init__(self, parent)
  2465. self.app = app
  2466. open_source_link = "<a href = 'https://opensource.org/'<b>Open Source</b></a>"
  2467. new_features_link = "<a href = 'https://bitbucket.org/jpcgt/flatcam/pull-requests/'" \
  2468. "<b>click</b></a>"
  2469. bugs_link = "<a href = 'https://bitbucket.org/jpcgt/flatcam/issues/new'<b>click</b></a>"
  2470. # donation_link = "<a href = 'https://www.paypal.com/cgi-bin/webscr?cmd=_" \
  2471. # "donations&business=WLTJJ3Q77D98L&currency_code=USD&source=url'<b>click</b></a>"
  2472. # Icon and title
  2473. self.setWindowIcon(parent.app_icon)
  2474. self.setWindowTitle(_("Important Information's"))
  2475. self.resize(750, 375)
  2476. logo = QtWidgets.QLabel()
  2477. logo.setPixmap(QtGui.QPixmap(self.app.resource_location + '/contribute256.png'))
  2478. # content = QtWidgets.QLabel(
  2479. # "%s<br>"
  2480. # "%s<br><br>"
  2481. # "%s,<br>"
  2482. # "%s<br>"
  2483. # "<ul>"
  2484. # "<li> &nbsp;%s %s</li>"
  2485. # "<li> &nbsp;%s %s</li>"
  2486. # "</ul>"
  2487. # "%s %s.<br>"
  2488. # "%s"
  2489. # "<ul>"
  2490. # "<li> &nbsp;%s &#128077;</li>"
  2491. # "<li> &nbsp;%s &#128513;</li>"
  2492. # "</ul>" %
  2493. # (
  2494. # _("This program is %s and free in a very wide meaning of the word.") % open_source_link,
  2495. # _("Yet it cannot evolve without <b>contributions</b>."),
  2496. # _("If you want to see this application grow and become better and better"),
  2497. # _("you can <b>contribute</b> to the development yourself by:"),
  2498. # _("Pull Requests on the Bitbucket repository, if you are a developer"),
  2499. # new_features_link,
  2500. # _("Bug Reports by providing the steps required to reproduce the bug"),
  2501. # bugs_link,
  2502. # _("If you like or use this program you can make a donation"),
  2503. # donation_link,
  2504. # _("You don't have to make a donation %s, and it is totally optional but:") % donation_link,
  2505. # _("it will be welcomed with joy"),
  2506. # _("it will give me a reason to continue")
  2507. # )
  2508. # )
  2509. content = QtWidgets.QLabel(
  2510. "%s<br>"
  2511. "%s<br><br>"
  2512. "%s,<br>"
  2513. "%s<br>"
  2514. "<ul>"
  2515. "<li> &nbsp;%s %s</li>"
  2516. "<li> &nbsp;%s %s</li>"
  2517. "</ul>" %
  2518. (
  2519. _("This program is %s and free in a very wide meaning of the word.") % open_source_link,
  2520. _("Yet it cannot evolve without <b>contributions</b>."),
  2521. _("If you want to see this application grow and become better and better"),
  2522. _("you can <b>contribute</b> to the development yourself by:"),
  2523. _("Pull Requests on the Bitbucket repository, if you are a developer"),
  2524. new_features_link,
  2525. _("Bug Reports by providing the steps required to reproduce the bug"),
  2526. bugs_link
  2527. )
  2528. )
  2529. content.setOpenExternalLinks(True)
  2530. # palette
  2531. pal = QtGui.QPalette()
  2532. pal.setColor(QtGui.QPalette.Background, Qt.white)
  2533. # layouts
  2534. main_layout = QtWidgets.QVBoxLayout()
  2535. self.setLayout(main_layout)
  2536. tab_layout = QtWidgets.QHBoxLayout()
  2537. buttons_hlay = QtWidgets.QHBoxLayout()
  2538. main_layout.addLayout(tab_layout)
  2539. main_layout.addLayout(buttons_hlay)
  2540. tab_widget = QtWidgets.QTabWidget()
  2541. tab_layout.addWidget(tab_widget)
  2542. closebtn = QtWidgets.QPushButton(_("Close"))
  2543. buttons_hlay.addStretch()
  2544. buttons_hlay.addWidget(closebtn)
  2545. # CONTRIBUTE section
  2546. self.intro_tab = QtWidgets.QWidget()
  2547. self.intro_tab_layout = QtWidgets.QHBoxLayout(self.intro_tab)
  2548. self.intro_tab_layout.setContentsMargins(2, 2, 2, 2)
  2549. tab_widget.addTab(self.intro_tab, _("Contribute"))
  2550. self.grid_lay = QtWidgets.QGridLayout()
  2551. self.grid_lay.setHorizontalSpacing(20)
  2552. self.grid_lay.setColumnStretch(0, 0)
  2553. self.grid_lay.setColumnStretch(1, 1)
  2554. intro_wdg = QtWidgets.QWidget()
  2555. intro_wdg.setLayout(self.grid_lay)
  2556. intro_scroll_area = QtWidgets.QScrollArea()
  2557. intro_scroll_area.setWidget(intro_wdg)
  2558. intro_scroll_area.setWidgetResizable(True)
  2559. intro_scroll_area.setFrameShape(QtWidgets.QFrame.NoFrame)
  2560. intro_scroll_area.setPalette(pal)
  2561. self.grid_lay.addWidget(logo, 0, 0)
  2562. self.grid_lay.addWidget(content, 0, 1)
  2563. self.intro_tab_layout.addWidget(intro_scroll_area)
  2564. # LINKS EXCHANGE section
  2565. self.links_tab = QtWidgets.QWidget()
  2566. self.links_tab_layout = QtWidgets.QVBoxLayout(self.links_tab)
  2567. self.links_tab_layout.setContentsMargins(2, 2, 2, 2)
  2568. tab_widget.addTab(self.links_tab, _("Links Exchange"))
  2569. self.links_lay = QtWidgets.QHBoxLayout()
  2570. links_wdg = QtWidgets.QWidget()
  2571. links_wdg.setLayout(self.links_lay)
  2572. links_scroll_area = QtWidgets.QScrollArea()
  2573. links_scroll_area.setWidget(links_wdg)
  2574. links_scroll_area.setWidgetResizable(True)
  2575. links_scroll_area.setFrameShape(QtWidgets.QFrame.NoFrame)
  2576. links_scroll_area.setPalette(pal)
  2577. self.links_lay.addWidget(QtWidgets.QLabel('%s' % _("Soon ...")), alignment=QtCore.Qt.AlignCenter)
  2578. self.links_tab_layout.addWidget(links_scroll_area)
  2579. # HOW TO section
  2580. self.howto_tab = QtWidgets.QWidget()
  2581. self.howto_tab_layout = QtWidgets.QVBoxLayout(self.howto_tab)
  2582. self.howto_tab_layout.setContentsMargins(2, 2, 2, 2)
  2583. tab_widget.addTab(self.howto_tab, _("How To's"))
  2584. self.howto_lay = QtWidgets.QHBoxLayout()
  2585. howto_wdg = QtWidgets.QWidget()
  2586. howto_wdg.setLayout(self.howto_lay)
  2587. howto_scroll_area = QtWidgets.QScrollArea()
  2588. howto_scroll_area.setWidget(howto_wdg)
  2589. howto_scroll_area.setWidgetResizable(True)
  2590. howto_scroll_area.setFrameShape(QtWidgets.QFrame.NoFrame)
  2591. howto_scroll_area.setPalette(pal)
  2592. self.howto_lay.addWidget(QtWidgets.QLabel('%s' % _("Soon ...")), alignment=QtCore.Qt.AlignCenter)
  2593. self.howto_tab_layout.addWidget(howto_scroll_area)
  2594. # BUTTONS section
  2595. closebtn.clicked.connect(self.accept)
  2596. ReadmeDialog(app=self, parent=self.ui).exec_()
  2597. def install_bookmarks(self, book_dict=None):
  2598. """
  2599. Install the bookmarks actions in the Help menu -> Bookmarks
  2600. :param book_dict: a dict having the actions text as keys and the weblinks as the values
  2601. :return: None
  2602. """
  2603. if book_dict is None:
  2604. self.defaults["global_bookmarks"].update(
  2605. {
  2606. '1': ['FlatCAM', "http://flatcam.org"],
  2607. '2': ['Backup Site', ""]
  2608. }
  2609. )
  2610. else:
  2611. self.defaults["global_bookmarks"].clear()
  2612. self.defaults["global_bookmarks"].update(book_dict)
  2613. # first try to disconnect if somehow they get connected from elsewhere
  2614. for act in self.ui.menuhelp_bookmarks.actions():
  2615. try:
  2616. act.triggered.disconnect()
  2617. except TypeError:
  2618. pass
  2619. # clear all actions except the last one who is the Bookmark manager
  2620. if act is self.ui.menuhelp_bookmarks.actions()[-1]:
  2621. pass
  2622. else:
  2623. self.ui.menuhelp_bookmarks.removeAction(act)
  2624. bm_limit = int(self.defaults["global_bookmarks_limit"])
  2625. if self.defaults["global_bookmarks"]:
  2626. # order the self.defaults["global_bookmarks"] dict keys by the value as integer
  2627. # the whole convoluted things is because when serializing the self.defaults (on app close or save)
  2628. # the JSON is first making the keys as strings (therefore I have to use strings too
  2629. # or do the conversion :(
  2630. # )
  2631. # and it is ordering them (actually I want that to make the defaults easy to search within) but making
  2632. # the '10' entry jsut after '1' therefore ordering as strings
  2633. sorted_bookmarks = sorted(list(self.defaults["global_bookmarks"].items())[:bm_limit],
  2634. key=lambda x: int(x[0]))
  2635. for entry, bookmark in sorted_bookmarks:
  2636. title = bookmark[0]
  2637. weblink = bookmark[1]
  2638. act = QtWidgets.QAction(parent=self.ui.menuhelp_bookmarks)
  2639. act.setText(title)
  2640. act.setIcon(QtGui.QIcon(self.resource_location + '/link16.png'))
  2641. # from here: https://stackoverflow.com/questions/20390323/pyqt-dynamic-generate-qmenu-action-and-connect
  2642. if title == 'Backup Site' and weblink == "":
  2643. act.triggered.connect(self.on_backup_site)
  2644. else:
  2645. act.triggered.connect(lambda sig, link=weblink: webbrowser.open(link))
  2646. self.ui.menuhelp_bookmarks.insertAction(self.ui.menuhelp_bookmarks_manager, act)
  2647. self.ui.menuhelp_bookmarks_manager.triggered.connect(self.on_bookmarks_manager)
  2648. def on_bookmarks_manager(self):
  2649. """
  2650. Adds the bookmark manager in a Tab in Plot Area
  2651. :return:
  2652. """
  2653. for idx in range(self.ui.plot_tab_area.count()):
  2654. if self.ui.plot_tab_area.tabText(idx) == _("Bookmarks Manager"):
  2655. # there can be only one instance of Bookmark Manager at one time
  2656. return
  2657. # BookDialog(app=self, storage=self.defaults["global_bookmarks"], parent=self.ui).exec_()
  2658. self.book_dialog_tab = BookmarkManager(app=self, storage=self.defaults["global_bookmarks"], parent=self.ui)
  2659. self.book_dialog_tab.setObjectName("bookmarks_tab")
  2660. # add the tab if it was closed
  2661. self.ui.plot_tab_area.addTab(self.book_dialog_tab, _("Bookmarks Manager"))
  2662. # delete the absolute and relative position and messages in the infobar
  2663. # self.ui.position_label.setText("")
  2664. # self.ui.rel_position_label.setText("")
  2665. # hide coordinates toolbars in the infobar while in DB
  2666. self.ui.coords_toolbar.hide()
  2667. self.ui.delta_coords_toolbar.hide()
  2668. # Switch plot_area to preferences page
  2669. self.ui.plot_tab_area.setCurrentWidget(self.book_dialog_tab)
  2670. def on_backup_site(self):
  2671. msgbox = QtWidgets.QMessageBox()
  2672. msgbox.setText(_("This entry will resolve to another website if:\n\n"
  2673. "1. FlatCAM.org website is down\n"
  2674. "2. Someone forked FlatCAM project and wants to point\n"
  2675. "to his own website\n\n"
  2676. "If you can't get any informations about FlatCAM beta\n"
  2677. "use the YouTube channel link from the Help menu."))
  2678. msgbox.setWindowTitle(_("Alternative website"))
  2679. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/globe16.png'))
  2680. msgbox.setIcon(QtWidgets.QMessageBox.Question)
  2681. bt_yes = msgbox.addButton(_('Close'), QtWidgets.QMessageBox.YesRole)
  2682. msgbox.setDefaultButton(bt_yes)
  2683. msgbox.exec_()
  2684. # response = msgbox.clickedButton()
  2685. def final_save(self):
  2686. """
  2687. Callback for doing a preferences save to file whenever the application is about to quit.
  2688. If the project has changes, it will ask the user to save the project.
  2689. :return: None
  2690. """
  2691. if self.save_in_progress:
  2692. self.inform.emit('[WARNING_NOTCL] %s' % _("Application is saving the project. Please wait ..."))
  2693. return
  2694. if self.should_we_save and self.collection.get_list():
  2695. msgbox = QtWidgets.QMessageBox()
  2696. msgbox.setText(_("There are files/objects modified in FlatCAM. "
  2697. "\n"
  2698. "Do you want to Save the project?"))
  2699. msgbox.setWindowTitle(_("Save changes"))
  2700. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  2701. msgbox.setIcon(QtWidgets.QMessageBox.Question)
  2702. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  2703. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  2704. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  2705. msgbox.setDefaultButton(bt_yes)
  2706. msgbox.exec_()
  2707. response = msgbox.clickedButton()
  2708. if response == bt_yes:
  2709. try:
  2710. self.trayIcon.hide()
  2711. except Exception:
  2712. pass
  2713. self.on_file_saveprojectas(use_thread=True, quit_action=True)
  2714. elif response == bt_no:
  2715. try:
  2716. self.trayIcon.hide()
  2717. except Exception:
  2718. pass
  2719. self.quit_application()
  2720. elif response == bt_cancel:
  2721. return
  2722. else:
  2723. try:
  2724. self.trayIcon.hide()
  2725. except Exception:
  2726. pass
  2727. self.quit_application()
  2728. def quit_application(self):
  2729. """
  2730. Called (as a pyslot or not) when the application is quit.
  2731. :return: None
  2732. """
  2733. # close editors before quiting the app, if they are open
  2734. if self.geo_editor.editor_active is True:
  2735. self.geo_editor.deactivate()
  2736. try:
  2737. self.geo_editor.disconnect()
  2738. except TypeError:
  2739. pass
  2740. log.debug("App.quit_application() --> Geo Editor deactivated.")
  2741. if self.exc_editor.editor_active is True:
  2742. self.exc_editor.deactivate()
  2743. try:
  2744. self.grb_editor.disconnect()
  2745. except TypeError:
  2746. pass
  2747. log.debug("App.quit_application() --> Excellon Editor deactivated.")
  2748. if self.grb_editor.editor_active is True:
  2749. self.grb_editor.deactivate_grb_editor()
  2750. try:
  2751. self.exc_editor.disconnect()
  2752. except TypeError:
  2753. pass
  2754. log.debug("App.quit_application() --> Gerber Editor deactivated.")
  2755. # disconnect the mouse events
  2756. if self.is_legacy:
  2757. self.plotcanvas.graph_event_disconnect(self.mm)
  2758. self.plotcanvas.graph_event_disconnect(self.mp)
  2759. self.plotcanvas.graph_event_disconnect(self.mr)
  2760. self.plotcanvas.graph_event_disconnect(self.mdc)
  2761. self.plotcanvas.graph_event_disconnect(self.kp)
  2762. else:
  2763. self.mm = self.plotcanvas.graph_event_disconnect('mouse_move', self.on_mouse_move_over_plot)
  2764. self.mp = self.plotcanvas.graph_event_disconnect('mouse_press', self.on_mouse_click_over_plot)
  2765. self.mr = self.plotcanvas.graph_event_disconnect('mouse_release', self.on_mouse_click_release_over_plot)
  2766. self.mdc = self.plotcanvas.graph_event_disconnect('mouse_double_click',
  2767. self.on_mouse_double_click_over_plot)
  2768. self.kp = self.plotcanvas.graph_event_disconnect('key_press', self.ui.keyPressEvent)
  2769. self.preferencesUiManager.save_defaults(silent=True)
  2770. log.debug("App.quit_application() --> App Defaults saved.")
  2771. if self.cmd_line_headless != 1:
  2772. # save app state to file
  2773. stgs = QSettings("Open Source", "FlatCAM")
  2774. stgs.setValue('saved_gui_state', self.ui.saveState())
  2775. stgs.setValue('maximized_gui', self.ui.isMaximized())
  2776. stgs.setValue(
  2777. 'language',
  2778. self.ui.general_defaults_form.general_app_group.language_cb.get_value()
  2779. )
  2780. stgs.setValue(
  2781. 'notebook_font_size',
  2782. self.ui.general_defaults_form.general_app_set_group.notebook_font_size_spinner.get_value()
  2783. )
  2784. stgs.setValue(
  2785. 'axis_font_size',
  2786. self.ui.general_defaults_form.general_app_set_group.axis_font_size_spinner.get_value()
  2787. )
  2788. stgs.setValue(
  2789. 'textbox_font_size',
  2790. self.ui.general_defaults_form.general_app_set_group.textbox_font_size_spinner.get_value()
  2791. )
  2792. stgs.setValue(
  2793. 'hud_font_size',
  2794. self.ui.general_defaults_form.general_app_set_group.hud_font_size_spinner.get_value()
  2795. )
  2796. stgs.setValue('toolbar_lock', self.ui.lock_action.isChecked())
  2797. stgs.setValue(
  2798. 'machinist',
  2799. 1 if self.ui.general_defaults_form.general_app_set_group.machinist_cb.get_value() else 0
  2800. )
  2801. # This will write the setting to the platform specific storage.
  2802. del stgs
  2803. log.debug("App.quit_application() --> App UI state saved.")
  2804. # try to quit the Socket opened by ArgsThread class
  2805. try:
  2806. # self.new_launch.thread_exit = True
  2807. # self.new_launch.listener.close()
  2808. self.new_launch.stop.emit()
  2809. except Exception as err:
  2810. log.debug("App.quit_application() --> %s" % str(err))
  2811. # try to quit the QThread that run ArgsThread class
  2812. try:
  2813. # del self.new_launch
  2814. self.listen_th.quit()
  2815. except Exception as e:
  2816. log.debug("App.quit_application() --> %s" % str(e))
  2817. # terminate workers
  2818. # self.workers.__del__()
  2819. self.clear_pool()
  2820. # quit app by signalling for self.kill_app() method
  2821. # self.close_app_signal.emit()
  2822. QtWidgets.qApp.quit()
  2823. sys.exit(0)
  2824. # When the main event loop is not started yet in which case the qApp.quit() will do nothing
  2825. # we use the following command
  2826. # minor_v = sys.version_info.minor
  2827. # if minor_v < 8:
  2828. # # make sure that the app closes
  2829. # sys.exit(0)
  2830. # else:
  2831. # os._exit(0) # fix to work with Python 3.8
  2832. @staticmethod
  2833. def kill_app():
  2834. QtWidgets.qApp.quit()
  2835. # When the main event loop is not started yet in which case the qApp.quit() will do nothing
  2836. # we use the following command
  2837. sys.exit(0)
  2838. def on_portable_checked(self, state):
  2839. """
  2840. Callback called when the checkbox in Preferences GUI is checked.
  2841. It will set the application as portable by creating the preferences and recent files in the
  2842. 'config' folder found in the FlatCAM installation folder.
  2843. :param state: boolean, the state of the checkbox when clicked/checked
  2844. :return:
  2845. """
  2846. line_no = 0
  2847. data = None
  2848. if sys.platform != 'win32':
  2849. # this won't work in Linux or MacOS
  2850. return
  2851. # test if the app was frozen and choose the path for the configuration file
  2852. if getattr(sys, "frozen", False) is True:
  2853. current_data_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config'
  2854. else:
  2855. current_data_path = os.path.dirname(os.path.realpath(__file__)) + '\\config'
  2856. config_file = current_data_path + '\\configuration.txt'
  2857. try:
  2858. with open(config_file, 'r') as f:
  2859. try:
  2860. data = f.readlines()
  2861. except Exception as e:
  2862. log.debug('App.__init__() -->%s' % str(e))
  2863. return
  2864. except FileNotFoundError:
  2865. pass
  2866. for line in data:
  2867. line = line.strip('\n')
  2868. param = str(line).rpartition('=')
  2869. if param[0] == 'portable':
  2870. break
  2871. line_no += 1
  2872. if state:
  2873. data[line_no] = 'portable=True\n'
  2874. # create the new defauults files
  2875. # create current_defaults.FlatConfig file if there is none
  2876. try:
  2877. f = open(current_data_path + '/current_defaults.FlatConfig')
  2878. f.close()
  2879. except IOError:
  2880. App.log.debug('Creating empty current_defaults.FlatConfig')
  2881. f = open(current_data_path + '/current_defaults.FlatConfig', 'w')
  2882. json.dump({}, f)
  2883. f.close()
  2884. # create factory_defaults.FlatConfig file if there is none
  2885. try:
  2886. f = open(current_data_path + '/factory_defaults.FlatConfig')
  2887. f.close()
  2888. except IOError:
  2889. App.log.debug('Creating empty factory_defaults.FlatConfig')
  2890. f = open(current_data_path + '/factory_defaults.FlatConfig', 'w')
  2891. json.dump({}, f)
  2892. f.close()
  2893. try:
  2894. f = open(current_data_path + '/recent.json')
  2895. f.close()
  2896. except IOError:
  2897. App.log.debug('Creating empty recent.json')
  2898. f = open(current_data_path + '/recent.json', 'w')
  2899. json.dump([], f)
  2900. f.close()
  2901. try:
  2902. fp = open(current_data_path + '/recent_projects.json')
  2903. fp.close()
  2904. except IOError:
  2905. App.log.debug('Creating empty recent_projects.json')
  2906. fp = open(current_data_path + '/recent_projects.json', 'w')
  2907. json.dump([], fp)
  2908. fp.close()
  2909. # save the current defaults to the new defaults file
  2910. self.preferencesUiManager.save_defaults(silent=True, data_path=current_data_path)
  2911. else:
  2912. data[line_no] = 'portable=False\n'
  2913. with open(config_file, 'w') as f:
  2914. f.writelines(data)
  2915. def on_register_files(self, obj_type=None):
  2916. """
  2917. Called whenever there is a need to register file extensions with FlatCAM.
  2918. Works only in Windows and should be called only when FlatCAM is run in Windows.
  2919. :param obj_type: the type of object to be register for.
  2920. Can be: 'gerber', 'excellon' or 'gcode'. 'geometry' is not used for the moment.
  2921. :return: None
  2922. """
  2923. log.debug("Manufacturing files extensions are registered with FlatCAM.")
  2924. new_reg_path = 'Software\\Classes\\'
  2925. # find if the current user is admin
  2926. try:
  2927. is_admin = os.getuid() == 0
  2928. except AttributeError:
  2929. is_admin = ctypes.windll.shell32.IsUserAnAdmin() == 1
  2930. if is_admin is True:
  2931. root_path = winreg.HKEY_LOCAL_MACHINE
  2932. else:
  2933. root_path = winreg.HKEY_CURRENT_USER
  2934. # create the keys
  2935. def set_reg(name, root_pth, new_reg_path, value):
  2936. try:
  2937. winreg.CreateKey(root_pth, new_reg_path)
  2938. with winreg.OpenKey(root_pth, new_reg_path, 0, winreg.KEY_WRITE) as registry_key:
  2939. winreg.SetValueEx(registry_key, name, 0, winreg.REG_SZ, value)
  2940. return True
  2941. except WindowsError:
  2942. return False
  2943. # delete key in registry
  2944. def delete_reg(root_pth, reg_path, key_to_del):
  2945. key_to_del_path = reg_path + key_to_del
  2946. try:
  2947. winreg.DeleteKey(root_pth, key_to_del_path)
  2948. return True
  2949. except WindowsError:
  2950. return False
  2951. if obj_type is None or obj_type == 'excellon':
  2952. exc_list = \
  2953. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  2954. exc_list = [x for x in exc_list if x != '']
  2955. # register all keys in the Preferences window
  2956. for ext in exc_list:
  2957. new_k = new_reg_path + '.%s' % ext
  2958. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  2959. # and unregister those that are no longer in the Preferences windows but are in the file
  2960. for ext in self.defaults["fa_excellon"].replace(' ', '').split(','):
  2961. if ext not in exc_list:
  2962. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  2963. # now write the updated extensions to the self.defaults
  2964. # new_ext = ''
  2965. # for ext in exc_list:
  2966. # new_ext = new_ext + ext + ', '
  2967. # self.defaults["fa_excellon"] = new_ext
  2968. self.inform.emit('[success] %s' % _("Selected Excellon file extensions registered with FlatCAM."))
  2969. if obj_type is None or obj_type == 'gcode':
  2970. gco_list = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  2971. gco_list = [x for x in gco_list if x != '']
  2972. # register all keys in the Preferences window
  2973. for ext in gco_list:
  2974. new_k = new_reg_path + '.%s' % ext
  2975. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  2976. # and unregister those that are no longer in the Preferences windows but are in the file
  2977. for ext in self.defaults["fa_gcode"].replace(' ', '').split(','):
  2978. if ext not in gco_list:
  2979. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  2980. # now write the updated extensions to the self.defaults
  2981. # new_ext = ''
  2982. # for ext in gco_list:
  2983. # new_ext = new_ext + ext + ', '
  2984. # self.defaults["fa_gcode"] = new_ext
  2985. self.inform.emit('[success] %s' %
  2986. _("Selected GCode file extensions registered with FlatCAM."))
  2987. if obj_type is None or obj_type == 'gerber':
  2988. grb_list = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  2989. grb_list = [x for x in grb_list if x != '']
  2990. # register all keys in the Preferences window
  2991. for ext in grb_list:
  2992. new_k = new_reg_path + '.%s' % ext
  2993. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  2994. # and unregister those that are no longer in the Preferences windows but are in the file
  2995. for ext in self.defaults["fa_gerber"].replace(' ', '').split(','):
  2996. if ext not in grb_list:
  2997. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  2998. # now write the updated extensions to the self.defaults
  2999. # new_ext = ''
  3000. # for ext in grb_list:
  3001. # new_ext = new_ext + ext + ', '
  3002. # self.defaults["fa_gerber"] = new_ext
  3003. self.inform.emit('[success] %s' %
  3004. _("Selected Gerber file extensions registered with FlatCAM."))
  3005. def add_extension(self, ext_type):
  3006. """
  3007. Add a file extension to the list for a specific object
  3008. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  3009. :return:
  3010. """
  3011. if ext_type == 'excellon':
  3012. new_ext = self.ui.util_defaults_form.fa_excellon_group.ext_entry.get_value()
  3013. if new_ext == '':
  3014. return
  3015. old_val = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  3016. if new_ext in old_val:
  3017. return
  3018. old_val.append(new_ext)
  3019. old_val.sort()
  3020. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(old_val))
  3021. if ext_type == 'gcode':
  3022. new_ext = self.ui.util_defaults_form.fa_gcode_group.ext_entry.get_value()
  3023. if new_ext == '':
  3024. return
  3025. old_val = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  3026. if new_ext in old_val:
  3027. return
  3028. old_val.append(new_ext)
  3029. old_val.sort()
  3030. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(old_val))
  3031. if ext_type == 'gerber':
  3032. new_ext = self.ui.util_defaults_form.fa_gerber_group.ext_entry.get_value()
  3033. if new_ext == '':
  3034. return
  3035. old_val = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  3036. if new_ext in old_val:
  3037. return
  3038. old_val.append(new_ext)
  3039. old_val.sort()
  3040. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(old_val))
  3041. if ext_type == 'keyword':
  3042. new_kw = self.ui.util_defaults_form.kw_group.kw_entry.get_value()
  3043. if new_kw == '':
  3044. return
  3045. old_val = self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  3046. if new_kw in old_val:
  3047. return
  3048. old_val.append(new_kw)
  3049. old_val.sort()
  3050. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(old_val))
  3051. # update the self.myKeywords so the model is updated
  3052. self.autocomplete_kw_list = \
  3053. self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  3054. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  3055. self.shell._edit.set_model_data(self.myKeywords)
  3056. def del_extension(self, ext_type):
  3057. """
  3058. Remove a file extension from the list for a specific object
  3059. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  3060. :return:
  3061. """
  3062. if ext_type == 'excellon':
  3063. new_ext = self.ui.util_defaults_form.fa_excellon_group.ext_entry.get_value()
  3064. if new_ext == '':
  3065. return
  3066. old_val = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  3067. if new_ext not in old_val:
  3068. return
  3069. old_val.remove(new_ext)
  3070. old_val.sort()
  3071. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(old_val))
  3072. if ext_type == 'gcode':
  3073. new_ext = self.ui.util_defaults_form.fa_gcode_group.ext_entry.get_value()
  3074. if new_ext == '':
  3075. return
  3076. old_val = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  3077. if new_ext not in old_val:
  3078. return
  3079. old_val.remove(new_ext)
  3080. old_val.sort()
  3081. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(old_val))
  3082. if ext_type == 'gerber':
  3083. new_ext = self.ui.util_defaults_form.fa_gerber_group.ext_entry.get_value()
  3084. if new_ext == '':
  3085. return
  3086. old_val = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  3087. if new_ext not in old_val:
  3088. return
  3089. old_val.remove(new_ext)
  3090. old_val.sort()
  3091. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(old_val))
  3092. if ext_type == 'keyword':
  3093. new_kw = self.ui.util_defaults_form.kw_group.kw_entry.get_value()
  3094. if new_kw == '':
  3095. return
  3096. old_val = self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  3097. if new_kw not in old_val:
  3098. return
  3099. old_val.remove(new_kw)
  3100. old_val.sort()
  3101. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(old_val))
  3102. # update the self.myKeywords so the model is updated
  3103. self.autocomplete_kw_list = \
  3104. self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  3105. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  3106. self.shell._edit.set_model_data(self.myKeywords)
  3107. def restore_extensions(self, ext_type):
  3108. """
  3109. Restore all file extensions associations with FlatCAM, for a specific object
  3110. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  3111. :return:
  3112. """
  3113. if ext_type == 'excellon':
  3114. # don't add 'txt' to the associations (too many files are .txt and not Excellon) but keep it in the list
  3115. # for the ability to open Excellon files with .txt extension
  3116. new_exc_list = deepcopy(self.exc_list)
  3117. try:
  3118. new_exc_list.remove('txt')
  3119. except ValueError:
  3120. pass
  3121. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(new_exc_list))
  3122. if ext_type == 'gcode':
  3123. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(self.gcode_list))
  3124. if ext_type == 'gerber':
  3125. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(self.grb_list))
  3126. if ext_type == 'keyword':
  3127. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(self.default_keywords))
  3128. # update the self.myKeywords so the model is updated
  3129. self.autocomplete_kw_list = self.default_keywords
  3130. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  3131. self.shell._edit.set_model_data(self.myKeywords)
  3132. def delete_all_extensions(self, ext_type):
  3133. """
  3134. Delete all file extensions associations with FlatCAM, for a specific object
  3135. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  3136. :return:
  3137. """
  3138. if ext_type == 'excellon':
  3139. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value('')
  3140. if ext_type == 'gcode':
  3141. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value('')
  3142. if ext_type == 'gerber':
  3143. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value('')
  3144. if ext_type == 'keyword':
  3145. self.ui.util_defaults_form.kw_group.kw_list_text.set_value('')
  3146. # update the self.myKeywords so the model is updated
  3147. self.myKeywords = self.tcl_commands_list + self.tcl_keywords
  3148. self.shell._edit.set_model_data(self.myKeywords)
  3149. def on_edit_join(self, name=None):
  3150. """
  3151. Callback for Edit->Join. Joins the selected geometry objects into
  3152. a new one.
  3153. :return: None
  3154. """
  3155. self.defaults.report_usage("on_edit_join()")
  3156. obj_name_single = str(name) if name else "Combo_SingleGeo"
  3157. obj_name_multi = str(name) if name else "Combo_MultiGeo"
  3158. geo_type_set = set()
  3159. objs = self.collection.get_selected()
  3160. if len(objs) < 2:
  3161. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  3162. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  3163. return 'fail'
  3164. for obj in objs:
  3165. geo_type_set.add(obj.multigeo)
  3166. # if len(geo_type_list) == 1 means that all list elements are the same
  3167. if len(geo_type_set) != 1:
  3168. self.inform.emit('[ERROR] %s' %
  3169. _("Failed join. The Geometry objects are of different types.\n"
  3170. "At least one is MultiGeo type and the other is SingleGeo type. A possibility is to "
  3171. "convert from one to another and retry joining \n"
  3172. "but in the case of converting from MultiGeo to SingleGeo, informations may be lost and "
  3173. "the result may not be what was expected. \n"
  3174. "Check the generated GCODE."))
  3175. return
  3176. fuse_tools = self.defaults["geometry_merge_fuse_tools"]
  3177. # if at least one True object is in the list then due of the previous check, all list elements are True objects
  3178. if True in geo_type_set:
  3179. def initialize(geo_obj, app):
  3180. GeometryObject.merge(geo_list=objs, geo_final=geo_obj, multigeo=True, fuse_tools=fuse_tools)
  3181. app.inform.emit('[success] %s.' % _("Geometry merging finished"))
  3182. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  3183. for v in geo_obj.tools.values():
  3184. v['data']['name'] = obj_name_multi
  3185. self.app_obj.new_object("geometry", obj_name_multi, initialize)
  3186. else:
  3187. def initialize(geo_obj, app):
  3188. GeometryObject.merge(geo_list=objs, geo_final=geo_obj, multigeo=False, fuse_tools=fuse_tools)
  3189. app.inform.emit('[success] %s.' % _("Geometry merging finished"))
  3190. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  3191. for v in geo_obj.tools.values():
  3192. v['data']['name'] = obj_name_single
  3193. self.app_obj.new_object("geometry", obj_name_single, initialize)
  3194. self.should_we_save = True
  3195. def on_edit_join_exc(self):
  3196. """
  3197. Callback for Edit->Join Excellon. Joins the selected Excellon objects into
  3198. a new Excellon.
  3199. :return: None
  3200. """
  3201. self.defaults.report_usage("on_edit_join_exc()")
  3202. objs = self.collection.get_selected()
  3203. for obj in objs:
  3204. if not isinstance(obj, ExcellonObject):
  3205. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Excellon joining works only on Excellon objects."))
  3206. return
  3207. if len(objs) < 2:
  3208. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  3209. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  3210. return 'fail'
  3211. fuse_tools = self.defaults["excellon_merge_fuse_tools"]
  3212. def initialize(exc_obj, app):
  3213. ExcellonObject.merge(exc_list=objs, exc_final=exc_obj, decimals=self.decimals, fuse_tools=fuse_tools)
  3214. app.inform.emit('[success] %s.' % _("Excellon merging finished"))
  3215. self.app_obj.new_object("excellon", 'Combo_Excellon', initialize)
  3216. self.should_we_save = True
  3217. def on_edit_join_grb(self):
  3218. """
  3219. Callback for Edit->Join Gerber. Joins the selected Gerber objects into
  3220. a new Gerber object.
  3221. :return: None
  3222. """
  3223. self.defaults.report_usage("on_edit_join_grb()")
  3224. objs = self.collection.get_selected()
  3225. for obj in objs:
  3226. if not isinstance(obj, GerberObject):
  3227. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Gerber joining works only on Gerber objects."))
  3228. return
  3229. if len(objs) < 2:
  3230. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  3231. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  3232. return 'fail'
  3233. def initialize(grb_obj, app):
  3234. GerberObject.merge(grb_list=objs, grb_final=grb_obj)
  3235. app.inform.emit('[success] %s.' % _("Gerber merging finished"))
  3236. self.app_obj.new_object("gerber", 'Combo_Gerber', initialize)
  3237. self.should_we_save = True
  3238. def on_convert_singlegeo_to_multigeo(self):
  3239. """
  3240. Called for converting a Geometry object from single-geo to multi-geo.
  3241. Single-geo Geometry objects store their geometry data into self.solid_geometry.
  3242. Multi-geo Geometry objects store their geometry data into the self.tools dictionary, each key (a tool actually)
  3243. having as a value another dictionary. This value dictionary has one of it's keys 'solid_geometry' which holds
  3244. the solid-geometry of that tool.
  3245. :return: None
  3246. """
  3247. self.defaults.report_usage("on_convert_singlegeo_to_multigeo()")
  3248. obj = self.collection.get_active()
  3249. if obj is None:
  3250. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Select a Geometry Object and try again."))
  3251. return
  3252. if not isinstance(obj, GeometryObject):
  3253. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Expected a GeometryObject, got"), type(obj)))
  3254. return
  3255. obj.multigeo = True
  3256. for tooluid, dict_value in obj.tools.items():
  3257. dict_value['solid_geometry'] = deepcopy(obj.solid_geometry)
  3258. if not isinstance(obj.solid_geometry, list):
  3259. obj.solid_geometry = [obj.solid_geometry]
  3260. # obj.solid_geometry[:] = []
  3261. obj.plot()
  3262. self.should_we_save = True
  3263. self.inform.emit('[success] %s' % _("A Geometry object was converted to MultiGeo type."))
  3264. def on_convert_multigeo_to_singlegeo(self):
  3265. """
  3266. Called for converting a Geometry object from multi-geo to single-geo.
  3267. Single-geo Geometry objects store their geometry data into self.solid_geometry.
  3268. Multi-geo Geometry objects store their geometry data into the self.tools dictionary, each key (a tool actually)
  3269. having as a value another dictionary. This value dictionary has one of it's keys 'solid_geometry' which holds
  3270. the solid-geometry of that tool.
  3271. :return: None
  3272. """
  3273. self.defaults.report_usage("on_convert_multigeo_to_singlegeo()")
  3274. obj = self.collection.get_active()
  3275. if obj is None:
  3276. self.inform.emit('[ERROR_NOTCL] %s' %
  3277. _("Failed. Select a Geometry Object and try again."))
  3278. return
  3279. if not isinstance(obj, GeometryObject):
  3280. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  3281. (_("Expected a GeometryObject, got"), type(obj)))
  3282. return
  3283. obj.multigeo = False
  3284. total_solid_geometry = []
  3285. for tooluid, dict_value in obj.tools.items():
  3286. total_solid_geometry += deepcopy(dict_value['solid_geometry'])
  3287. # clear the original geometry
  3288. dict_value['solid_geometry'][:] = []
  3289. obj.solid_geometry = deepcopy(total_solid_geometry)
  3290. obj.plot()
  3291. self.should_we_save = True
  3292. self.inform.emit('[success] %s' %
  3293. _("A Geometry object was converted to SingleGeo type."))
  3294. def on_defaults_dict_change(self, field):
  3295. """
  3296. Called whenever a key changed in the self.defaults dictionary. It will set the required GUI element in the
  3297. Edit -> Preferences tab window.
  3298. :param field: the key of the self.defaults dictionary that was changed.
  3299. :return: None
  3300. """
  3301. self.preferencesUiManager.defaults_write_form_field(field=field)
  3302. if field == "units":
  3303. self.set_screen_units(self.defaults['units'])
  3304. def set_screen_units(self, units):
  3305. """
  3306. Set the FlatCAM units on the status bar.
  3307. :param units: the new measuring units to be displayed in FlatCAM's status bar.
  3308. :return: None
  3309. """
  3310. self.ui.units_label.setText("[" + units.lower() + "]")
  3311. def on_toggle_units_click(self):
  3312. try:
  3313. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.disconnect()
  3314. except (TypeError, AttributeError):
  3315. pass
  3316. if self.defaults["units"] == 'MM':
  3317. self.ui.general_defaults_form.general_app_group.units_radio.set_value("IN")
  3318. else:
  3319. self.ui.general_defaults_form.general_app_group.units_radio.set_value("MM")
  3320. self.on_toggle_units(no_pref=True)
  3321. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.connect(
  3322. lambda: self.on_toggle_units(no_pref=False))
  3323. def scale_defaults(self, sfactor, dimensions):
  3324. for dim in dimensions:
  3325. if dim in ['geometry_cnctooldia', 'tools_ncc_tools', 'tools_solderpaste_tools', 'tools_iso_tooldia',
  3326. 'tools_paint_tooldia', 'tools_transform_ref_point', 'tools_cal_toolchange_xy',
  3327. 'gerber_editor_newdim', 'tools_drill_toolchangexy', 'tools_drill_endxy',
  3328. 'geometry_toolchangexy', 'geometry_endxy', 'tools_solderpaste_xy_toolchange']:
  3329. if not self.defaults[dim] or self.defaults[dim] == '':
  3330. continue
  3331. if isinstance(self.defaults[dim], str):
  3332. try:
  3333. tools_diameters = eval(self.defaults[dim])
  3334. except Exception as e:
  3335. log.debug("App.on_toggle_units().scale_defaults() lists --> %s" % str(e))
  3336. continue
  3337. elif isinstance(self.defaults[dim], (float, int)):
  3338. tools_diameters = [self.defaults[dim]]
  3339. else:
  3340. tools_diameters = list(self.defaults[dim])
  3341. if isinstance(tools_diameters, (tuple, list)):
  3342. pass
  3343. elif isinstance(tools_diameters, (int, float)):
  3344. tools_diameters = [self.defaults[dim]]
  3345. else:
  3346. continue
  3347. td_len = len(tools_diameters)
  3348. conv_list = []
  3349. for t in range(td_len):
  3350. conv_list.append(self.dec_format(float(tools_diameters[t]) * sfactor, self.decimals))
  3351. self.defaults[dim] = conv_list
  3352. elif dim in ['global_gridx', 'global_gridy']:
  3353. # format the number of decimals to the one specified in self.decimals
  3354. try:
  3355. val = float(self.defaults[dim]) * sfactor
  3356. except Exception as e:
  3357. log.debug('App.on_toggle_units().scale_defaults() grids --> %s' % str(e))
  3358. continue
  3359. self.defaults[dim] = self.dec_format(val, self.decimals)
  3360. else:
  3361. # the number of decimals for the rest is kept unchanged
  3362. if self.defaults[dim]:
  3363. try:
  3364. val = float(self.defaults[dim]) * sfactor
  3365. except Exception as e:
  3366. log.debug(
  3367. 'App.on_toggle_units().scale_defaults() standard --> Value: %s %s' % (str(dim), str(e))
  3368. )
  3369. continue
  3370. self.defaults[dim] = self.dec_format(val, self.decimals)
  3371. def on_toggle_units(self, no_pref=False):
  3372. """
  3373. Callback for the Units radio-button change in the Preferences tab.
  3374. Changes the application's default units adn for the project too.
  3375. If changing the project's units, the change propagates to all of
  3376. the objects in the project.
  3377. :return: None
  3378. """
  3379. self.defaults.report_usage("on_toggle_units")
  3380. if self.toggle_units_ignore:
  3381. return
  3382. new_units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  3383. # If option is the same, then ignore
  3384. if new_units == self.defaults["units"].upper():
  3385. self.log.debug("on_toggle_units(): Same as previous, ignoring.")
  3386. return
  3387. # Keys in self.defaults for which to scale their values
  3388. dimensions = [
  3389. # Global
  3390. 'global_gridx', 'global_gridy', 'global_snap_max', "global_tolerance",
  3391. 'global_tpdf_bmargin', 'global_tpdf_tmargin', 'global_tpdf_rmargin', 'global_tpdf_lmargin',
  3392. # Gerber Object
  3393. 'gerber_noncoppermargin', 'gerber_bboxmargin',
  3394. # Gerber Editor
  3395. "gerber_editor_newsize", "gerber_editor_lin_pitch", "gerber_editor_buff_f",
  3396. "gerber_editor_newdim", "gerber_editor_ma_low", "gerber_editor_ma_high",
  3397. # Excellon Object
  3398. "excellon_milling_dia", 'excellon_tooldia', 'excellon_slot_tooldia',
  3399. # Excellon Editor
  3400. "excellon_editor_newdia", "excellon_editor_lin_pitch", "excellon_editor_slot_lin_pitch",
  3401. "excellon_editor_slot_length",
  3402. # Geometry Object
  3403. 'geometry_cutz', "geometry_depthperpass", 'geometry_travelz', 'geometry_feedrate',
  3404. 'geometry_feedrate_rapid', "geometry_toolchangez", "geometry_feedrate_z",
  3405. "geometry_toolchangexy", 'geometry_cnctooldia', 'geometry_endz', 'geometry_endxy',
  3406. "geometry_extracut_length", "geometry_z_pdepth",
  3407. "geometry_feedrate_probe", "geometry_startz", "geometry_segx", "geometry_segy", "geometry_area_overz",
  3408. # CNCJob Object
  3409. 'cncjob_tooldia', "cncjob_al_travelz", "cncjob_al_probe_depth", "cncjob_al_grbl_jog_step",
  3410. "cncjob_al_grbl_jog_fr", "cncjob_al_grbl_travelz",
  3411. # Isolation Tool
  3412. "tools_iso_tool_vtipdia", 'tools_iso_tooldia', "tools_iso_tool_cutz",
  3413. # Drilling Tool
  3414. 'tools_drill_cutz', 'tools_drill_depthperpass', 'tools_drill_travelz', 'tools_drill_endz',
  3415. 'tools_drill_endxy', 'tools_drill_feedrate_z', 'tools_drill_toolchangez', "tools_drill_drill_overlap",
  3416. 'tools_drill_offset', "tools_drill_toolchangexy", "tools_drill_startz", 'tools_drill_feedrate_rapid',
  3417. "tools_drill_feedrate_probe", "tools_drill_z_pdepth", "tools_drill_area_overz",
  3418. # NCC Tool
  3419. "tools_ncc_tools", "tools_ncc_margin", "tools_ncc_offset_value", "tools_ncc_cutz", "tools_ncc_tipdia",
  3420. "tools_ncc_newdia",
  3421. # Cutout Tool
  3422. "tools_cutout_tooldia", 'tools_cutout_margin', "tools_cutout_z", "tools_cutout_depthperpass",
  3423. 'tools_cutout_gapsize', 'tools_cutout_gap_depth', 'tools_cutout_mb_dia', 'tools_cutout_mb_spacing',
  3424. # Paint Tool
  3425. "tools_paint_tooldia", 'tools_paint_offset', "tools_paint_cutz", "tools_paint_tipdia", "tools_paint_newdia",
  3426. # 2Sided Tool
  3427. "tools_2sided_drilldia",
  3428. # Film Tool
  3429. "tools_film_boundary", "tools_film_scale_stroke",
  3430. # Panel Tool
  3431. "tools_panelize_spacing_columns", "tools_panelize_spacing_rows", "tools_panelize_constrainx",
  3432. "tools_panelize_constrainy",
  3433. # Calculators Tool
  3434. "tools_calc_vshape_tip_dia", "tools_calc_vshape_cut_z",
  3435. # Transform Tool
  3436. "tools_transform_ref_point", "tools_transform_offset_x", "tools_transform_offset_y",
  3437. "tools_transform_buffer_dis",
  3438. # SolderPaste Tool
  3439. "tools_solderpaste_tools", "tools_solderpaste_new", "tools_solderpaste_z_start",
  3440. "tools_solderpaste_z_dispense", "tools_solderpaste_z_stop", "tools_solderpaste_z_travel",
  3441. "tools_solderpaste_z_toolchange", "tools_solderpaste_xy_toolchange", "tools_solderpaste_frxy",
  3442. "tools_solderpaste_frz", "tools_solderpaste_frz_dispense",
  3443. # Corner Markers Tool
  3444. "tools_corners_thickness", "tools_corners_length", "tools_corners_margin",
  3445. # Check Rules Tool
  3446. "tools_cr_trace_size_val", "tools_cr_c2c_val", "tools_cr_c2o_val", "tools_cr_s2s_val", "tools_cr_s2sm_val",
  3447. "tools_cr_s2o_val", "tools_cr_sm2sm_val", "tools_cr_ri_val", "tools_cr_h2h_val", "tools_cr_dh_val",
  3448. # QRCode Tool
  3449. "tools_qrcode_border_size",
  3450. # Copper Thieving Tool
  3451. "tools_copper_thieving_clearance", "tools_copper_thieving_margin",
  3452. "tools_copper_thieving_dots_dia", "tools_copper_thieving_dots_spacing",
  3453. "tools_copper_thieving_squares_size", "tools_copper_thieving_squares_spacing",
  3454. "tools_copper_thieving_lines_size", "tools_copper_thieving_lines_spacing",
  3455. "tools_copper_thieving_rb_margin", "tools_copper_thieving_rb_thickness",
  3456. "tools_copper_thieving_mask_clearance",
  3457. # Fiducials Tool
  3458. "tools_fiducials_dia", "tools_fiducials_margin", "tools_fiducials_line_thickness",
  3459. # Calibration Tool
  3460. "tools_cal_travelz", "tools_cal_verz", "tools_cal_toolchangez", "tools_cal_toolchange_xy",
  3461. # Drills Extraction Tool
  3462. "tools_edrills_hole_fixed_dia", "tools_edrills_circular_ring", "tools_edrills_oblong_ring",
  3463. "tools_edrills_square_ring", "tools_edrills_rectangular_ring", "tools_edrills_others_ring",
  3464. # Punch Gerber Tool
  3465. "tools_punch_hole_fixed_dia", "tools_punch_circular_ring", "tools_punch_oblong_ring",
  3466. "tools_punch_square_ring", "tools_punch_rectangular_ring", "tools_punch_others_ring",
  3467. # Invert Gerber Tool
  3468. "tools_invert_margin",
  3469. ]
  3470. # The scaling factor depending on choice of units.
  3471. factor = 25.4 if new_units == 'MM' else 1 / 25.4
  3472. # Changing project units. Warn user.
  3473. msgbox = QtWidgets.QMessageBox()
  3474. msgbox.setWindowTitle(_("Toggle Units"))
  3475. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/toggle_units32.png'))
  3476. msgbox.setIcon(QtWidgets.QMessageBox.Question)
  3477. msgbox.setText(_("Changing the units of the project\n"
  3478. "will scale all objects.\n\n"
  3479. "Do you want to continue?"))
  3480. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  3481. msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  3482. msgbox.setDefaultButton(bt_ok)
  3483. msgbox.exec_()
  3484. response = msgbox.clickedButton()
  3485. if response == bt_ok:
  3486. if no_pref is False:
  3487. self.preferencesUiManager.defaults_read_form()
  3488. self.scale_defaults(factor, dimensions)
  3489. self.preferencesUiManager.defaults_write_form(fl_units=new_units)
  3490. self.defaults["units"] = new_units
  3491. # update the defaults from form, some may assume that the conversion is enough and it's not
  3492. self.on_options_app2project()
  3493. # update the objects
  3494. for obj in self.collection.get_list():
  3495. obj.convert_units(new_units)
  3496. # make that the properties stored in the object are also updated
  3497. self.app_obj.object_changed.emit(obj)
  3498. # rebuild the object UI
  3499. obj.build_ui()
  3500. # change this only if the workspace is active
  3501. if self.defaults['global_workspace'] is True:
  3502. self.plotcanvas.draw_workspace(pagesize=self.defaults['global_workspaceT'])
  3503. # adjust the grid values on the main toolbar
  3504. val_x = float(self.defaults['global_gridx']) * factor
  3505. val_y = val_x if self.ui.grid_gap_link_cb.isChecked() else float(self.defaults['global_gridx']) * factor
  3506. current = self.collection.get_active()
  3507. if current is not None:
  3508. # the transfer of converted values to the UI form for Geometry is done local in the FlatCAMObj.py
  3509. if not isinstance(current, GeometryObject):
  3510. current.to_form()
  3511. # replot all objects
  3512. self.plot_all()
  3513. # set the status labels to reflect the current FlatCAM units
  3514. self.set_screen_units(new_units)
  3515. # signal to the app that we changed the object properties and it should save the project
  3516. self.should_we_save = True
  3517. self.inform.emit('[success] %s: %s' % (_("Converted units to"), new_units))
  3518. else:
  3519. # Undo toggling
  3520. self.toggle_units_ignore = True
  3521. if self.defaults['units'].upper() == 'MM':
  3522. self.ui.general_defaults_form.general_app_group.units_radio.set_value('IN')
  3523. else:
  3524. self.ui.general_defaults_form.general_app_group.units_radio.set_value('MM')
  3525. self.toggle_units_ignore = False
  3526. # store the grid values so they are not changed in the next step
  3527. val_x = float(self.defaults['global_gridx'])
  3528. val_y = float(self.defaults['global_gridy'])
  3529. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  3530. self.preferencesUiManager.defaults_read_form()
  3531. # the self.preferencesUiManager.defaults_read_form() will update all defaults values
  3532. # in self.defaults from the GUI elements but
  3533. # I don't want it for the grid values, so I update them here
  3534. self.defaults['global_gridx'] = val_x
  3535. self.defaults['global_gridy'] = val_y
  3536. self.ui.grid_gap_x_entry.set_value(val_x, decimals=self.decimals)
  3537. self.ui.grid_gap_y_entry.set_value(val_y, decimals=self.decimals)
  3538. def on_deselect_all(self):
  3539. self.collection.set_all_inactive()
  3540. self.delete_selection_shape()
  3541. def on_workspace_modified(self):
  3542. # self.save_defaults(silent=True)
  3543. self.plotcanvas.delete_workspace()
  3544. self.preferencesUiManager.defaults_read_form()
  3545. self.plotcanvas.draw_workspace(workspace_size=self.defaults['global_workspaceT'])
  3546. def on_workspace(self):
  3547. if self.ui.general_defaults_form.general_app_set_group.workspace_cb.get_value():
  3548. self.plotcanvas.draw_workspace(workspace_size=self.defaults['global_workspaceT'])
  3549. self.inform[str, bool].emit(_("Workspace enabled."), False)
  3550. else:
  3551. self.plotcanvas.delete_workspace()
  3552. self.inform[str, bool].emit(_("Workspace disabled."), False)
  3553. self.preferencesUiManager.defaults_read_form()
  3554. # self.save_defaults(silent=True)
  3555. def on_workspace_toggle(self):
  3556. state = False if self.ui.general_defaults_form.general_app_set_group.workspace_cb.get_value() else True
  3557. try:
  3558. self.ui.general_defaults_form.general_app_set_group.workspace_cb.stateChanged.disconnect(self.on_workspace)
  3559. except TypeError:
  3560. pass
  3561. self.ui.general_defaults_form.general_app_set_group.workspace_cb.set_value(state)
  3562. self.ui.general_defaults_form.general_app_set_group.workspace_cb.stateChanged.connect(self.on_workspace)
  3563. self.on_workspace()
  3564. def on_cursor_type(self, val):
  3565. """
  3566. :param val: type of mouse cursor, set in Preferences ('small' or 'big')
  3567. :return: None
  3568. """
  3569. self.app_cursor.enabled = False
  3570. if val == 'small':
  3571. self.ui.general_defaults_form.general_app_set_group.cursor_size_entry.setDisabled(False)
  3572. self.ui.general_defaults_form.general_app_set_group.cursor_size_lbl.setDisabled(False)
  3573. self.app_cursor = self.plotcanvas.new_cursor()
  3574. else:
  3575. self.ui.general_defaults_form.general_app_set_group.cursor_size_entry.setDisabled(True)
  3576. self.ui.general_defaults_form.general_app_set_group.cursor_size_lbl.setDisabled(True)
  3577. self.app_cursor = self.plotcanvas.new_cursor(big=True)
  3578. if self.ui.grid_snap_btn.isChecked():
  3579. self.app_cursor.enabled = True
  3580. else:
  3581. self.app_cursor.enabled = False
  3582. def on_tool_add_keypress(self):
  3583. # ## Current application units in Upper Case
  3584. self.units = self.defaults['units'].upper()
  3585. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  3586. # work only if the notebook tab on focus is the properties_tab and only if the object is Geometry
  3587. if notebook_widget_name == 'properties_tab':
  3588. if self.collection.get_active().kind == 'geometry':
  3589. # Tool add works for Geometry only if Advanced is True in Preferences
  3590. if self.defaults["global_app_level"] == 'a':
  3591. tool_add_popup = FCInputDialog(title="New Tool ...",
  3592. text='Enter a Tool Diameter:',
  3593. min=0.0000, max=99.9999, decimals=4)
  3594. tool_add_popup.setWindowIcon(QtGui.QIcon(self.resource_location + '/letter_t_32.png'))
  3595. val, ok = tool_add_popup.get_value()
  3596. if ok:
  3597. if float(val) == 0:
  3598. self.inform.emit('[WARNING_NOTCL] %s' %
  3599. _("Please enter a tool diameter with non-zero value, in Float format."))
  3600. return
  3601. self.collection.get_active().on_tool_add(dia=float(val))
  3602. else:
  3603. self.inform.emit('[WARNING_NOTCL] %s...' % _("Adding Tool cancelled"))
  3604. else:
  3605. msgbox = QtWidgets.QMessageBox()
  3606. msgbox.setText(_("Adding Tool works only when Advanced is checked.\n"
  3607. "Go to Preferences -> General - Show Advanced Options."))
  3608. msgbox.setWindowTitle("Tool adding ...")
  3609. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/warning.png'))
  3610. msgbox.setIcon(QtWidgets.QMessageBox.Warning)
  3611. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  3612. msgbox.setDefaultButton(bt_ok)
  3613. msgbox.exec_()
  3614. # work only if the notebook tab on focus is the Tools_Tab
  3615. if notebook_widget_name == 'tool_tab':
  3616. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  3617. # and only if the tool is NCC Tool
  3618. if tool_widget == self.ncclear_tool.toolName:
  3619. self.ncclear_tool.on_add_tool_by_key()
  3620. # and only if the tool is Paint Area Tool
  3621. elif tool_widget == self.paint_tool.toolName:
  3622. self.paint_tool.on_add_tool_by_key()
  3623. # and only if the tool is Solder Paste Dispensing Tool
  3624. elif tool_widget == self.paste_tool.toolName:
  3625. self.paste_tool.on_add_tool_by_key()
  3626. # It's meant to delete tools in tool tables via a 'Delete' shortcut key but only if certain conditions are met
  3627. # See description below.
  3628. def on_delete_keypress(self):
  3629. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  3630. # work only if the notebook tab on focus is the properties_tab and only if the object is Geometry
  3631. if notebook_widget_name == 'properties_tab':
  3632. if str(type(self.collection.get_active())) == "<class 'FlatCAMObj.GeometryObject'>":
  3633. self.collection.get_active().on_tool_delete()
  3634. # work only if the notebook tab on focus is the Tools_Tab
  3635. elif notebook_widget_name == 'tool_tab':
  3636. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  3637. # and only if the tool is NCC Tool
  3638. if tool_widget == self.ncclear_tool.toolName:
  3639. self.ncclear_tool.on_tool_delete()
  3640. # and only if the tool is Paint Tool
  3641. elif tool_widget == self.paint_tool.toolName:
  3642. self.paint_tool.on_tool_delete()
  3643. # and only if the tool is Solder Paste Dispensing Tool
  3644. elif tool_widget == self.paste_tool.toolName:
  3645. self.paste_tool.on_tool_delete()
  3646. # and only if the tool is Isolation Tool
  3647. elif tool_widget == self.isolation_tool.toolName:
  3648. self.isolation_tool.on_tool_delete()
  3649. else:
  3650. self.on_delete()
  3651. # It's meant to delete selected objects. It work also activated by a shortcut key 'Delete' same as above so in
  3652. # some screens you have to be careful where you hover with your mouse.
  3653. # Hovering over Selected tab, if the selected tab is a Geometry it will delete tools in tool table. But even if
  3654. # there is a Selected tab in focus with a Geometry inside, if you hover over canvas it will delete an object.
  3655. # Complicated, I know :)
  3656. def on_delete(self, force_deletion=False):
  3657. """
  3658. Delete the currently selected FlatCAMObjs.
  3659. :param force_deletion: used by Tcl command
  3660. :return: None
  3661. """
  3662. self.defaults.report_usage("on_delete()")
  3663. response = None
  3664. bt_ok = None
  3665. # Make sure that the deletion will happen only after the Editor is no longer active otherwise we might delete
  3666. # a geometry object before we update it.
  3667. if self.geo_editor.editor_active is False and self.exc_editor.editor_active is False \
  3668. and self.grb_editor.editor_active is False and self.gcode_editor.editor_active is False:
  3669. if self.defaults["global_delete_confirmation"] is True and force_deletion is False:
  3670. msgbox = QtWidgets.QMessageBox()
  3671. msgbox.setWindowTitle(_("Delete objects"))
  3672. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/deleteshape32.png'))
  3673. msgbox.setIcon(QtWidgets.QMessageBox.Question)
  3674. # msgbox.setText("<B>%s</B>" % _("Change project units ..."))
  3675. msgbox.setText(_("Are you sure you want to permanently delete\n"
  3676. "the selected objects?"))
  3677. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  3678. msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  3679. msgbox.setDefaultButton(bt_ok)
  3680. msgbox.exec_()
  3681. response = msgbox.clickedButton()
  3682. if self.defaults["global_delete_confirmation"] is False or force_deletion is True:
  3683. response = bt_ok
  3684. if response == bt_ok:
  3685. if self.collection.get_active():
  3686. self.log.debug("App.on_delete()")
  3687. for obj_active in self.collection.get_selected():
  3688. # if the deleted object is GerberObject then make sure to delete the possible mark shapes
  3689. if obj_active.kind == 'gerber':
  3690. obj_active.mark_shapes_storage.clear()
  3691. obj_active.mark_shapes.clear(update=True)
  3692. obj_active.mark_shapes.enabled = False
  3693. elif obj_active.kind == 'cncjob':
  3694. try:
  3695. obj_active.text_col.enabled = False
  3696. del obj_active.text_col
  3697. obj_active.annotation.clear(update=True)
  3698. del obj_active.annotation
  3699. obj_active.probing_shapes.clear(update=True)
  3700. except AttributeError as e:
  3701. log.debug(
  3702. "App.on_delete() --> delete annotations on a FlatCAMCNCJob object. %s" % str(e)
  3703. )
  3704. while self.collection.get_selected():
  3705. self.delete_first_selected()
  3706. # make sure that the selection shape is deleted, too
  3707. self.delete_selection_shape()
  3708. # if there are no longer objects delete also the exclusion areas shapes
  3709. if not self.collection.get_list():
  3710. self.exc_areas.clear_shapes()
  3711. self.inform.emit('%s...' % _("Object(s) deleted"))
  3712. else:
  3713. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. No object(s) selected..."))
  3714. else:
  3715. self.inform.emit(_("Save the work in Editor and try again ..."))
  3716. def delete_first_selected(self):
  3717. # Keep this for later
  3718. try:
  3719. sel_obj = self.collection.get_active()
  3720. name = sel_obj.options["name"]
  3721. isPlotted = sel_obj.options["plot"]
  3722. except AttributeError:
  3723. self.log.debug("Nothing selected for deletion")
  3724. return
  3725. if self.is_legacy is True:
  3726. # Remove plot only if the object was plotted otherwise delaxes will fail
  3727. if isPlotted:
  3728. try:
  3729. # self.plotcanvas.figure.delaxes(self.collection.get_active().axes)
  3730. self.plotcanvas.figure.delaxes(self.collection.get_active().shapes.axes)
  3731. except Exception as e:
  3732. log.debug("App.delete_first_selected() --> %s" % str(e))
  3733. self.plotcanvas.auto_adjust_axes()
  3734. # Remove from dictionary
  3735. self.collection.delete_active()
  3736. # Clear form
  3737. self.setup_default_properties_tab()
  3738. self.inform.emit('%s: %s' % (_("Object deleted"), name))
  3739. def on_set_origin(self):
  3740. """
  3741. Set the origin to the left mouse click position
  3742. :return: None
  3743. """
  3744. # display the message for the user
  3745. # and ask him to click on the desired position
  3746. self.defaults.report_usage("on_set_origin()")
  3747. def origin_replot():
  3748. def worker_task():
  3749. with self.proc_container.new('%s...' % _("Plotting")):
  3750. for obj in self.collection.get_list():
  3751. obj.plot()
  3752. self.plotcanvas.fit_view()
  3753. if self.is_legacy:
  3754. self.plotcanvas.graph_event_disconnect(self.mp_zc)
  3755. else:
  3756. self.plotcanvas.graph_event_disconnect('mouse_press', self.on_set_zero_click)
  3757. self.worker_task.emit({'fcn': worker_task, 'params': []})
  3758. self.inform.emit(_('Click to set the origin ...'))
  3759. self.mp_zc = self.plotcanvas.graph_event_connect('mouse_press', self.on_set_zero_click)
  3760. # first disconnect it as it may have been used by something else
  3761. try:
  3762. self.replot_signal.disconnect()
  3763. except TypeError:
  3764. pass
  3765. self.replot_signal[list].connect(origin_replot)
  3766. def on_set_zero_click(self, event, location=None, noplot=False, use_thread=True):
  3767. """
  3768. :param event:
  3769. :param location:
  3770. :param noplot:
  3771. :param use_thread:
  3772. :return:
  3773. """
  3774. noplot_sig = noplot
  3775. def worker_task():
  3776. with self.proc_container.new(_("Setting Origin...")):
  3777. obj_list = self.collection.get_list()
  3778. for obj in obj_list:
  3779. obj.offset((x, y))
  3780. self.app_obj.object_changed.emit(obj)
  3781. # Update the object bounding box options
  3782. a, b, c, d = obj.bounds()
  3783. obj.options['xmin'] = a
  3784. obj.options['ymin'] = b
  3785. obj.options['xmax'] = c
  3786. obj.options['ymax'] = d
  3787. self.inform.emit('[success] %s...' % _('Origin set'))
  3788. for obj in obj_list:
  3789. out_name = obj.options["name"]
  3790. if obj.kind == 'gerber':
  3791. obj.source_file = self.f_handlers.export_gerber(
  3792. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  3793. elif obj.kind == 'excellon':
  3794. obj.source_file = self.f_handlers.export_excellon(
  3795. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  3796. if noplot_sig is False:
  3797. self.replot_signal.emit([])
  3798. if location is not None:
  3799. if len(location) != 2:
  3800. self.inform.emit('[ERROR_NOTCL] %s...' % _("Origin coordinates specified but incomplete."))
  3801. return 'fail'
  3802. x, y = location
  3803. if use_thread is True:
  3804. self.worker_task.emit({'fcn': worker_task, 'params': []})
  3805. else:
  3806. worker_task()
  3807. self.should_we_save = True
  3808. return
  3809. if event is not None and event.button == 1:
  3810. if self.is_legacy is False:
  3811. event_pos = event.pos
  3812. else:
  3813. event_pos = (event.xdata, event.ydata)
  3814. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  3815. if self.grid_status():
  3816. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  3817. else:
  3818. pos = pos_canvas
  3819. x = 0 - pos[0]
  3820. y = 0 - pos[1]
  3821. if use_thread is True:
  3822. self.worker_task.emit({'fcn': worker_task, 'params': []})
  3823. else:
  3824. worker_task()
  3825. self.should_we_save = True
  3826. def on_move2origin(self, use_thread=True):
  3827. """
  3828. Move selected objects to origin.
  3829. :param use_thread: Control if to use threaded operation. Boolean.
  3830. :return:
  3831. """
  3832. def worker_task():
  3833. with self.proc_container.new(_("Moving to Origin...")):
  3834. obj_list = self.collection.get_selected()
  3835. if not obj_list:
  3836. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. No object(s) selected..."))
  3837. return
  3838. xminlist = []
  3839. yminlist = []
  3840. # first get a bounding box to fit all
  3841. for obj in obj_list:
  3842. xmin, ymin, xmax, ymax = obj.bounds()
  3843. xminlist.append(xmin)
  3844. yminlist.append(ymin)
  3845. # get the minimum x,y for all objects selected
  3846. x = min(xminlist)
  3847. y = min(yminlist)
  3848. for obj in obj_list:
  3849. obj.offset((-x, -y))
  3850. self.app_obj.object_changed.emit(obj)
  3851. # Update the object bounding box options
  3852. a, b, c, d = obj.bounds()
  3853. obj.options['xmin'] = a
  3854. obj.options['ymin'] = b
  3855. obj.options['xmax'] = c
  3856. obj.options['ymax'] = d
  3857. for obj in obj_list:
  3858. obj.plot()
  3859. for obj in obj_list:
  3860. out_name = obj.options["name"]
  3861. if obj.kind == 'gerber':
  3862. obj.source_file = self.f_handlers.export_gerber(
  3863. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  3864. elif obj.kind == 'excellon':
  3865. obj.source_file = self.f_handlers.export_excellon(
  3866. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  3867. self.inform.emit('[success] %s...' % _('Origin set'))
  3868. if use_thread is True:
  3869. self.worker_task.emit({'fcn': worker_task, 'params': []})
  3870. else:
  3871. worker_task()
  3872. self.should_we_save = True
  3873. def on_jump_to(self, custom_location=None, fit_center=True):
  3874. """
  3875. Jump to a location by setting the mouse cursor location.
  3876. :param custom_location: Jump to a specified point. (x, y) tuple.
  3877. :param fit_center: If to fit view. Boolean.
  3878. :return:
  3879. """
  3880. self.defaults.report_usage("on_jump_to()")
  3881. if not custom_location:
  3882. dia_box_location = None
  3883. try:
  3884. dia_box_location = eval(self.clipboard.text())
  3885. except Exception:
  3886. pass
  3887. if type(dia_box_location) == tuple:
  3888. dia_box_location = str(dia_box_location)
  3889. else:
  3890. dia_box_location = None
  3891. # dia_box = Dialog_box(title=_("Jump to ..."),
  3892. # label=_("Enter the coordinates in format X,Y:"),
  3893. # icon=QtGui.QIcon(self.resource_location + '/jump_to16.png'),
  3894. # initial_text=dia_box_location)
  3895. dia_box = DialogBoxRadio(title=_("Jump to ..."),
  3896. label=_("Enter the coordinates in format X,Y:"),
  3897. icon=QtGui.QIcon(self.resource_location + '/jump_to16.png'),
  3898. initial_text=dia_box_location,
  3899. reference=self.defaults['global_jump_ref'])
  3900. if dia_box.ok is True:
  3901. try:
  3902. location = eval(dia_box.location)
  3903. if not isinstance(location, tuple):
  3904. self.inform.emit(_("Wrong coordinates. Enter coordinates in format: X,Y"))
  3905. return
  3906. if dia_box.reference == 'rel':
  3907. rel_x = self.mouse[0] + location[0]
  3908. rel_y = self.mouse[1] + location[1]
  3909. location = (rel_x, rel_y)
  3910. self.defaults['global_jump_ref'] = dia_box.reference
  3911. except Exception:
  3912. return
  3913. else:
  3914. return
  3915. else:
  3916. location = custom_location
  3917. self.jump_signal.emit(location)
  3918. if fit_center:
  3919. self.plotcanvas.fit_center(loc=location)
  3920. cursor = QtGui.QCursor()
  3921. if self.is_legacy is False:
  3922. # I don't know where those differences come from but they are constant for the current
  3923. # execution of the application and they are multiples of a value around 0.0263mm.
  3924. # In a random way sometimes they are more sometimes they are less
  3925. # if units == 'MM':
  3926. # cal_factor = 0.0263
  3927. # else:
  3928. # cal_factor = 0.0263 / 25.4
  3929. cal_location = (location[0], location[1])
  3930. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  3931. jump_loc = self.plotcanvas.translate_coords_2((cal_location[0], cal_location[1]))
  3932. j_pos = (
  3933. int(canvas_origin.x() + round(jump_loc[0])),
  3934. int(canvas_origin.y() + round(jump_loc[1]))
  3935. )
  3936. cursor.setPos(j_pos[0], j_pos[1])
  3937. else:
  3938. # find the canvas origin which is in the top left corner
  3939. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  3940. # determine the coordinates for the lowest left point of the canvas
  3941. x0, y0 = canvas_origin.x(), canvas_origin.y() + self.ui.right_layout.geometry().height()
  3942. # transform the given location from data coordinates to display coordinates. THe display coordinates are
  3943. # in pixels where the origin 0,0 is in the lowest left point of the display window (in our case is the
  3944. # canvas) and the point (width, height) is in the top-right location
  3945. loc = self.plotcanvas.axes.transData.transform_point(location)
  3946. j_pos = (
  3947. int(x0 + loc[0]),
  3948. int(y0 - loc[1])
  3949. )
  3950. cursor.setPos(j_pos[0], j_pos[1])
  3951. self.plotcanvas.mouse = [location[0], location[1]]
  3952. if self.defaults["global_cursor_color_enabled"] is True:
  3953. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1], color=self.cursor_color_3D)
  3954. else:
  3955. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1])
  3956. if self.grid_status():
  3957. # Update cursor
  3958. self.app_cursor.set_data(np.asarray([(location[0], location[1])]),
  3959. symbol='++', edge_color=self.cursor_color_3D,
  3960. edge_width=self.defaults["global_cursor_width"],
  3961. size=self.defaults["global_cursor_size"])
  3962. # Set the relative position label
  3963. dx = location[0] - float(self.rel_point1[0])
  3964. dy = location[1] - float(self.rel_point1[1])
  3965. self.ui.position_label.setText("&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  3966. "<b>Y</b>: %.4f&nbsp;" % (location[0], location[1]))
  3967. # Set the position label
  3968. self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  3969. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (dx, dy))
  3970. units = self.defaults["units"].lower()
  3971. self.plotcanvas.text_hud.text = \
  3972. 'Dx:\t{:<.4f} [{:s}]\nDy:\t{:<.4f} [{:s}]\n\nX: \t{:<.4f} [{:s}]\nY: \t{:<.4f} [{:s}]'.format(
  3973. dx, units, dy, units, location[0], units, location[1], units)
  3974. self.inform.emit('[success] %s' % _("Done."))
  3975. return location
  3976. def on_locate(self, obj, fit_center=True):
  3977. """
  3978. Jump to one of the corners (or center) of an object by setting the mouse cursor location
  3979. :param obj: The object on which to locate certain points
  3980. :param fit_center: If to fit view. Boolean.
  3981. :return: A point location. (x, y) tuple.
  3982. """
  3983. self.defaults.report_usage("on_locate()")
  3984. if obj is None:
  3985. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  3986. return 'fail'
  3987. class DialogBoxChoice(QtWidgets.QDialog):
  3988. def __init__(self, title=None, icon=None, choice='bl'):
  3989. """
  3990. :param title: string with the window title
  3991. """
  3992. super(DialogBoxChoice, self).__init__()
  3993. self.ok = False
  3994. self.setWindowIcon(icon)
  3995. self.setWindowTitle(str(title))
  3996. self.form = QtWidgets.QFormLayout(self)
  3997. self.ref_radio = RadioSet([
  3998. {"label": _("Bottom-Left"), "value": "bl"},
  3999. {"label": _("Top-Left"), "value": "tl"},
  4000. {"label": _("Bottom-Right"), "value": "br"},
  4001. {"label": _("Top-Right"), "value": "tr"},
  4002. {"label": _("Center"), "value": "c"}
  4003. ], orientation='vertical', stretch=False)
  4004. self.ref_radio.set_value(choice)
  4005. self.form.addRow(self.ref_radio)
  4006. self.button_box = QtWidgets.QDialogButtonBox(
  4007. QtWidgets.QDialogButtonBox.Ok | QtWidgets.QDialogButtonBox.Cancel,
  4008. Qt.Horizontal, parent=self)
  4009. self.form.addRow(self.button_box)
  4010. self.button_box.accepted.connect(self.accept)
  4011. self.button_box.rejected.connect(self.reject)
  4012. if self.exec_() == QtWidgets.QDialog.Accepted:
  4013. self.ok = True
  4014. self.location_point = self.ref_radio.get_value()
  4015. else:
  4016. self.ok = False
  4017. self.location_point = None
  4018. dia_box = DialogBoxChoice(title=_("Locate ..."),
  4019. icon=QtGui.QIcon(self.resource_location + '/locate16.png'),
  4020. choice=self.defaults['global_locate_pt'])
  4021. if dia_box.ok is True:
  4022. try:
  4023. location_point = dia_box.location_point
  4024. self.defaults['global_locate_pt'] = dia_box.location_point
  4025. except Exception:
  4026. return
  4027. else:
  4028. return
  4029. loc_b = obj.bounds()
  4030. if location_point == 'bl':
  4031. location = (loc_b[0], loc_b[1])
  4032. elif location_point == 'tl':
  4033. location = (loc_b[0], loc_b[3])
  4034. elif location_point == 'br':
  4035. location = (loc_b[2], loc_b[1])
  4036. elif location_point == 'tr':
  4037. location = (loc_b[2], loc_b[3])
  4038. else:
  4039. # center
  4040. cx = loc_b[0] + ((loc_b[2] - loc_b[0]) / 2)
  4041. cy = loc_b[1] + ((loc_b[3] - loc_b[1]) / 2)
  4042. location = (cx, cy)
  4043. self.locate_signal.emit(location, location_point)
  4044. if fit_center:
  4045. self.plotcanvas.fit_center(loc=location)
  4046. cursor = QtGui.QCursor()
  4047. if self.is_legacy is False:
  4048. # I don't know where those differences come from but they are constant for the current
  4049. # execution of the application and they are multiples of a value around 0.0263mm.
  4050. # In a random way sometimes they are more sometimes they are less
  4051. # if units == 'MM':
  4052. # cal_factor = 0.0263
  4053. # else:
  4054. # cal_factor = 0.0263 / 25.4
  4055. cal_location = (location[0], location[1])
  4056. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  4057. jump_loc = self.plotcanvas.translate_coords_2((cal_location[0], cal_location[1]))
  4058. j_pos = (
  4059. int(canvas_origin.x() + round(jump_loc[0])),
  4060. int(canvas_origin.y() + round(jump_loc[1]))
  4061. )
  4062. cursor.setPos(j_pos[0], j_pos[1])
  4063. else:
  4064. # find the canvas origin which is in the top left corner
  4065. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  4066. # determine the coordinates for the lowest left point of the canvas
  4067. x0, y0 = canvas_origin.x(), canvas_origin.y() + self.ui.right_layout.geometry().height()
  4068. # transform the given location from data coordinates to display coordinates. THe display coordinates are
  4069. # in pixels where the origin 0,0 is in the lowest left point of the display window (in our case is the
  4070. # canvas) and the point (width, height) is in the top-right location
  4071. loc = self.plotcanvas.axes.transData.transform_point(location)
  4072. j_pos = (
  4073. int(x0 + loc[0]),
  4074. int(y0 - loc[1])
  4075. )
  4076. cursor.setPos(j_pos[0], j_pos[1])
  4077. self.plotcanvas.mouse = [location[0], location[1]]
  4078. if self.defaults["global_cursor_color_enabled"] is True:
  4079. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1], color=self.cursor_color_3D)
  4080. else:
  4081. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1])
  4082. if self.grid_status():
  4083. # Update cursor
  4084. self.app_cursor.set_data(np.asarray([(location[0], location[1])]),
  4085. symbol='++', edge_color=self.cursor_color_3D,
  4086. edge_width=self.defaults["global_cursor_width"],
  4087. size=self.defaults["global_cursor_size"])
  4088. # Set the relative position label
  4089. self.dx = location[0] - float(self.rel_point1[0])
  4090. self.dy = location[1] - float(self.rel_point1[1])
  4091. # Set the position label
  4092. self.ui.position_label.setText("&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  4093. "<b>Y</b>: %.4f&nbsp;" % (location[0], location[1]))
  4094. self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  4095. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (self.dx, self.dy))
  4096. units = self.defaults["units"].lower()
  4097. self.plotcanvas.text_hud.text = \
  4098. 'Dx:\t{:<.4f} [{:s}]\nDy:\t{:<.4f} [{:s}]\n\nX: \t{:<.4f} [{:s}]\nY: \t{:<.4f} [{:s}]'.format(
  4099. self.dx, units, self.dy, units, location[0], units, location[1], units)
  4100. self.inform.emit('[success] %s' % _("Done."))
  4101. return location
  4102. def on_copy_command(self):
  4103. """
  4104. Will copy a selection of objects, creating new objects.
  4105. :return:
  4106. """
  4107. self.defaults.report_usage("on_copy_command()")
  4108. def initialize(obj_init, app):
  4109. """
  4110. :param obj_init: the new object
  4111. :type obj_init: class
  4112. :param app: An instance of the App class
  4113. :type app: App
  4114. :return: None
  4115. :rtype:
  4116. """
  4117. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  4118. try:
  4119. obj_init.follow_geometry = deepcopy(obj.follow_geometry)
  4120. except AttributeError:
  4121. pass
  4122. try:
  4123. obj_init.apertures = deepcopy(obj.apertures)
  4124. except AttributeError:
  4125. pass
  4126. try:
  4127. if obj.tools:
  4128. obj_init.tools = deepcopy(obj.tools)
  4129. except Exception as err:
  4130. log.debug("App.on_copy_command() --> %s" % str(err))
  4131. try:
  4132. obj_init.source_file = deepcopy(obj.source_file)
  4133. except (AttributeError, TypeError):
  4134. pass
  4135. def initialize_excellon(obj_init, app):
  4136. obj_init.source_file = deepcopy(obj.source_file)
  4137. obj_init.tools = deepcopy(obj.tools)
  4138. # drills are offset, so they need to be deep copied
  4139. obj_init.drills = deepcopy(obj.drills)
  4140. # slots are offset, so they need to be deep copied
  4141. obj_init.slots = deepcopy(obj.slots)
  4142. obj_init.create_geometry()
  4143. def initialize_script(obj_init, app_obj):
  4144. obj_init.source_file = deepcopy(obj.source_file)
  4145. def initialize_document(obj_init, app_obj):
  4146. obj_init.source_file = deepcopy(obj.source_file)
  4147. for obj in self.collection.get_selected():
  4148. obj_name = obj.options["name"]
  4149. try:
  4150. if isinstance(obj, ExcellonObject):
  4151. self.app_obj.new_object("excellon", str(obj_name) + "_copy", initialize_excellon)
  4152. elif isinstance(obj, GerberObject):
  4153. self.app_obj.new_object("gerber", str(obj_name) + "_copy", initialize)
  4154. elif isinstance(obj, GeometryObject):
  4155. self.app_obj.new_object("geometry", str(obj_name) + "_copy", initialize)
  4156. elif isinstance(obj, ScriptObject):
  4157. self.app_obj.new_object("script", str(obj_name) + "_copy", initialize_script)
  4158. elif isinstance(obj, DocumentObject):
  4159. self.app_obj.new_object("document", str(obj_name) + "_copy", initialize_document)
  4160. except Exception as e:
  4161. return "Operation failed: %s" % str(e)
  4162. def on_copy_object2(self, custom_name):
  4163. def initialize_geometry(obj_init, app):
  4164. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  4165. try:
  4166. obj_init.follow_geometry = deepcopy(obj.follow_geometry)
  4167. except AttributeError:
  4168. pass
  4169. try:
  4170. obj_init.apertures = deepcopy(obj.apertures)
  4171. except AttributeError:
  4172. pass
  4173. try:
  4174. if obj.tools:
  4175. obj_init.tools = deepcopy(obj.tools)
  4176. except Exception as ee:
  4177. log.debug("on_copy_object2() --> %s" % str(ee))
  4178. def initialize_gerber(obj_init, app):
  4179. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  4180. obj_init.apertures = deepcopy(obj.apertures)
  4181. obj_init.aperture_macros = deepcopy(obj.aperture_macros)
  4182. def initialize_excellon(obj_init, app):
  4183. obj_init.tools = deepcopy(obj.tools)
  4184. # drills are offset, so they need to be deep copied
  4185. obj_init.drills = deepcopy(obj.drills)
  4186. # slots are offset, so they need to be deep copied
  4187. obj_init.slots = deepcopy(obj.slots)
  4188. obj_init.create_geometry()
  4189. for obj in self.collection.get_selected():
  4190. obj_name = obj.options["name"]
  4191. try:
  4192. if isinstance(obj, ExcellonObject):
  4193. self.app_obj.new_object("excellon", str(obj_name) + custom_name, initialize_excellon)
  4194. elif isinstance(obj, GerberObject):
  4195. self.app_obj.new_object("gerber", str(obj_name) + custom_name, initialize_gerber)
  4196. elif isinstance(obj, GeometryObject):
  4197. self.app_obj.new_object("geometry", str(obj_name) + custom_name, initialize_geometry)
  4198. except Exception as er:
  4199. return "Operation failed: %s" % str(er)
  4200. def on_rename_object(self, text):
  4201. """
  4202. Will rename an object.
  4203. :param text: New name for the object.
  4204. :return:
  4205. """
  4206. self.defaults.report_usage("on_rename_object()")
  4207. named_obj = self.collection.get_active()
  4208. for obj in named_obj:
  4209. if obj is list:
  4210. self.on_rename_object(text)
  4211. else:
  4212. try:
  4213. obj.options['name'] = text
  4214. except Exception as e:
  4215. log.warning("App.on_rename_object() --> Could not rename the object in the list. --> %s" % str(e))
  4216. def convert_any2geo(self):
  4217. """
  4218. Will convert any object out of Gerber, Excellon, Geometry to Geometry object.
  4219. :return:
  4220. """
  4221. self.defaults.report_usage("convert_any2geo()")
  4222. def initialize(obj_init, app):
  4223. obj_init.solid_geometry = obj.solid_geometry
  4224. try:
  4225. obj_init.follow_geometry = obj.follow_geometry
  4226. except AttributeError:
  4227. pass
  4228. try:
  4229. obj_init.apertures = obj.apertures
  4230. except AttributeError:
  4231. pass
  4232. try:
  4233. if obj.tools:
  4234. obj_init.tools = obj.tools
  4235. except AttributeError:
  4236. pass
  4237. def initialize_excellon(obj_init, app):
  4238. # objs = self.collection.get_selected()
  4239. # GeometryObject.merge(objs, obj)
  4240. solid_geo = []
  4241. for tool in obj.tools:
  4242. for geo in obj.tools[tool]['solid_geometry']:
  4243. solid_geo.append(geo)
  4244. obj_init.solid_geometry = deepcopy(solid_geo)
  4245. if not self.collection.get_selected():
  4246. log.warning("App.convert_any2geo --> No object selected")
  4247. self.inform.emit('[WARNING_NOTCL] %s' %
  4248. _("No object is selected. Select an object and try again."))
  4249. return
  4250. for obj in self.collection.get_selected():
  4251. obj_name = obj.options["name"]
  4252. try:
  4253. if obj.kind == 'excellon':
  4254. self.app_obj.new_object("geometry", str(obj_name) + "_conv", initialize_excellon)
  4255. else:
  4256. self.app_obj.new_object("geometry", str(obj_name) + "_conv", initialize)
  4257. except Exception as e:
  4258. return "Operation failed: %s" % str(e)
  4259. def convert_any2gerber(self):
  4260. """
  4261. Will convert any object out of Gerber, Excellon, Geometry to Gerber object.
  4262. :return:
  4263. """
  4264. def initialize_geometry(obj_init, app):
  4265. apertures = {}
  4266. apid = 0
  4267. apertures[str(apid)] = {}
  4268. apertures[str(apid)]['geometry'] = []
  4269. for obj_orig in obj.solid_geometry:
  4270. new_elem = {}
  4271. new_elem['solid'] = obj_orig
  4272. try:
  4273. new_elem['follow'] = obj_orig.exterior
  4274. except AttributeError:
  4275. pass
  4276. apertures[str(apid)]['geometry'].append(deepcopy(new_elem))
  4277. apertures[str(apid)]['size'] = 0.0
  4278. apertures[str(apid)]['type'] = 'C'
  4279. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  4280. obj_init.apertures = deepcopy(apertures)
  4281. def initialize_excellon(obj_init, app):
  4282. apertures = {}
  4283. apid = 10
  4284. for tool in obj.tools:
  4285. apertures[str(apid)] = {}
  4286. apertures[str(apid)]['geometry'] = []
  4287. for geo in obj.tools[tool]['solid_geometry']:
  4288. new_el = {}
  4289. new_el['solid'] = geo
  4290. new_el['follow'] = geo.exterior
  4291. apertures[str(apid)]['geometry'].append(deepcopy(new_el))
  4292. apertures[str(apid)]['size'] = float(obj.tools[tool]['C'])
  4293. apertures[str(apid)]['type'] = 'C'
  4294. apid += 1
  4295. # create solid_geometry
  4296. solid_geometry = []
  4297. for apid in apertures:
  4298. for geo_el in apertures[apid]['geometry']:
  4299. solid_geometry.append(geo_el['solid'])
  4300. solid_geometry = MultiPolygon(solid_geometry)
  4301. solid_geometry = solid_geometry.buffer(0.0000001)
  4302. obj_init.solid_geometry = deepcopy(solid_geometry)
  4303. obj_init.apertures = deepcopy(apertures)
  4304. # clear the working objects (perhaps not necessary due of Python GC)
  4305. apertures.clear()
  4306. if not self.collection.get_selected():
  4307. log.warning("App.convert_any2gerber --> No object selected")
  4308. self.inform.emit('[WARNING_NOTCL] %s' %
  4309. _("No object is selected. Select an object and try again."))
  4310. return
  4311. for obj in self.collection.get_selected():
  4312. obj_name = obj.options["name"]
  4313. try:
  4314. if obj.kind == 'excellon':
  4315. self.app_obj.new_object("gerber", str(obj_name) + "_conv", initialize_excellon)
  4316. elif obj.kind == 'geometry':
  4317. self.app_obj.new_object("gerber", str(obj_name) + "_conv", initialize_geometry)
  4318. else:
  4319. log.warning("App.convert_any2gerber --> This is no valid object for conversion.")
  4320. except Exception as e:
  4321. return "Operation failed: %s" % str(e)
  4322. def convert_any2excellon(self):
  4323. """
  4324. Will convert any object out of Gerber, Excellon, Geometry to an Excellon object.
  4325. :return:
  4326. """
  4327. def initialize_geometry(obj_init, app):
  4328. tools = {}
  4329. tooluid = 1
  4330. obj_init.solid_geometry = []
  4331. for geo in obj.solid_geometry:
  4332. if not isinstance(geo, (Polygon, MultiPolygon, LinearRing)):
  4333. continue
  4334. minx, miny, maxx, maxy = geo.bounds
  4335. new_dia = min([maxx-minx, maxy-miny])
  4336. new_drill = geo.centroid
  4337. new_drill_geo = new_drill.buffer(new_dia / 2.0)
  4338. current_tooldias = []
  4339. if tools:
  4340. for tool in tools:
  4341. if tools[tool] and 'tooldia' in tools[tool]:
  4342. current_tooldias.append(tools[tool]['tooldia'])
  4343. if new_dia in current_tooldias:
  4344. for tool in tools:
  4345. if float('%.*f' % (self.decimals, tools[tool]["tooldia"])) == float('%.*f' % (self.decimals,
  4346. new_dia)):
  4347. tools[tool]['drills'].append(new_drill)
  4348. tools[tool]['solid_geometry'].append(deepcopy(new_drill_geo))
  4349. else:
  4350. tools[tooluid] = {}
  4351. tools[tooluid]['tooldia'] = new_dia
  4352. tools[tooluid]['drills'] = [new_drill]
  4353. tools[tooluid]['slots'] = []
  4354. tools[tooluid]['solid_geometry'] = [new_drill_geo]
  4355. tooluid += 1
  4356. try:
  4357. obj_init.solid_geometry.append(new_drill_geo)
  4358. except (TypeError, AttributeError):
  4359. obj_init.solid_geometry = [new_drill_geo]
  4360. obj_init.tools = deepcopy(tools)
  4361. obj_init.solid_geometry = unary_union(obj_init.solid_geometry)
  4362. def initialize_gerber(obj_init, app):
  4363. tools = {}
  4364. tooluid = 1
  4365. obj_init.solid_geometry = []
  4366. for apid in obj.apertures:
  4367. if 'geometry' in obj.apertures[apid]:
  4368. for geo_dict in obj.apertures[apid]['geometry']:
  4369. if 'follow' in geo_dict:
  4370. if isinstance(geo_dict['follow'], Point):
  4371. geo = geo_dict['solid']
  4372. minx, miny, maxx, maxy = geo.bounds
  4373. new_dia = min([maxx - minx, maxy - miny])
  4374. new_drill = geo.centroid
  4375. new_drill_geo = new_drill.buffer(new_dia / 2.0)
  4376. current_tooldias = []
  4377. if tools:
  4378. for tool in tools:
  4379. if tools[tool] and 'tooldia' in tools[tool]:
  4380. current_tooldias.append(
  4381. float('%.*f' % (self.decimals, tools[tool]['tooldia']))
  4382. )
  4383. if float('%.*f' % (self.decimals, new_dia)) in current_tooldias:
  4384. for tool in tools:
  4385. if float('%.*f' % (self.decimals, tools[tool]["tooldia"])) == float(
  4386. '%.*f' % (self.decimals, new_dia)):
  4387. if new_drill not in tools[tool]['drills']:
  4388. tools[tool]['drills'].append(new_drill)
  4389. tools[tool]['solid_geometry'].append(deepcopy(new_drill_geo))
  4390. else:
  4391. tools[tooluid] = {}
  4392. tools[tooluid]['tooldia'] = new_dia
  4393. tools[tooluid]['drills'] = [new_drill]
  4394. tools[tooluid]['slots'] = []
  4395. tools[tooluid]['solid_geometry'] = [new_drill_geo]
  4396. tooluid += 1
  4397. try:
  4398. obj_init.solid_geometry.append(new_drill_geo)
  4399. except (TypeError, AttributeError):
  4400. obj_init.solid_geometry = [new_drill_geo]
  4401. elif isinstance(geo_dict['follow'], LineString):
  4402. geo_coords = list(geo_dict['follow'].coords)
  4403. # slots can have only a start and stop point and no intermediate points
  4404. if len(geo_coords) != 2:
  4405. continue
  4406. geo = geo_dict['solid']
  4407. try:
  4408. new_dia = obj.apertures[apid]['size']
  4409. except Exception:
  4410. continue
  4411. new_slot = (Point(geo_coords[0]), Point(geo_coords[1]))
  4412. new_slot_geo = geo
  4413. current_tooldias = []
  4414. if tools:
  4415. for tool in tools:
  4416. if tools[tool] and 'tooldia' in tools[tool]:
  4417. current_tooldias.append(
  4418. float('%.*f' % (self.decimals, tools[tool]['tooldia']))
  4419. )
  4420. if float('%.*f' % (self.decimals, new_dia)) in current_tooldias:
  4421. for tool in tools:
  4422. if float('%.*f' % (self.decimals, tools[tool]["tooldia"])) == float(
  4423. '%.*f' % (self.decimals, new_dia)):
  4424. if new_slot not in tools[tool]['slots']:
  4425. tools[tool]['slots'].append(new_slot)
  4426. tools[tool]['solid_geometry'].append(deepcopy(new_slot_geo))
  4427. else:
  4428. tools[tooluid] = {}
  4429. tools[tooluid]['tooldia'] = new_dia
  4430. tools[tooluid]['drills'] = []
  4431. tools[tooluid]['slots'] = [new_slot]
  4432. tools[tooluid]['solid_geometry'] = [new_slot_geo]
  4433. tooluid += 1
  4434. try:
  4435. obj_init.solid_geometry.append(new_slot_geo)
  4436. except (TypeError, AttributeError):
  4437. obj_init.solid_geometry = [new_slot_geo]
  4438. obj_init.tools = deepcopy(tools)
  4439. obj_init.solid_geometry = unary_union(obj_init.solid_geometry)
  4440. if not self.collection.get_selected():
  4441. log.warning("App.convert_any2excellon--> No object selected")
  4442. self.inform.emit('[WARNING_NOTCL] %s' % _("No object is selected. Select an object and try again."))
  4443. return
  4444. for obj in self.collection.get_selected():
  4445. obj_name = obj.options["name"]
  4446. try:
  4447. if obj.kind == 'gerber':
  4448. self.app_obj.new_object("excellon", str(obj_name) + "_conv", initialize_gerber)
  4449. elif obj.kind == 'geometry':
  4450. self.app_obj.new_object("excellon", str(obj_name) + "_conv", initialize_geometry)
  4451. else:
  4452. log.warning("App.convert_any2excellon --> This is no valid object for conversion.")
  4453. except Exception as e:
  4454. return "Operation failed: %s" % str(e)
  4455. def abort_all_tasks(self):
  4456. """
  4457. Executed when a certain key combo is pressed (Ctrl+Alt+X). Will abort current task
  4458. on the first possible occasion.
  4459. :return:
  4460. """
  4461. if self.abort_flag is False:
  4462. self.inform.emit(_("Aborting. The current task will be gracefully closed as soon as possible..."))
  4463. self.abort_flag = True
  4464. self.cleanup.emit()
  4465. def app_is_idle(self):
  4466. if self.abort_flag:
  4467. self.inform.emit('[WARNING_NOTCL] %s' % _("The current task was gracefully closed on user request..."))
  4468. self.abort_flag = False
  4469. def on_selectall(self):
  4470. """
  4471. Will draw a selection box shape around the selected objects.
  4472. :return:
  4473. """
  4474. self.defaults.report_usage("on_selectall()")
  4475. # delete the possible selection box around a possible selected object
  4476. self.delete_selection_shape()
  4477. for name in self.collection.get_names():
  4478. self.collection.set_active(name)
  4479. curr_sel_obj = self.collection.get_by_name(name)
  4480. # create the selection box around the selected object
  4481. if self.defaults['global_selection_shape'] is True:
  4482. self.draw_selection_shape(curr_sel_obj)
  4483. def on_toggle_preferences(self):
  4484. pref_open = False
  4485. for idx in range(self.ui.plot_tab_area.count()):
  4486. if self.ui.plot_tab_area.tabText(idx) == _("Preferences"):
  4487. pref_open = True
  4488. if pref_open:
  4489. for idx in range(self.ui.plot_tab_area.count()):
  4490. if self.ui.plot_tab_area.tabText(idx) == _("Preferences"):
  4491. self.ui.plot_tab_area.removeTab(idx)
  4492. break
  4493. self.ui.pref_status_label.setStyleSheet("")
  4494. else:
  4495. self.on_preferences()
  4496. def on_preferences(self):
  4497. """
  4498. Adds the Preferences in a Tab in Plot Area
  4499. :return:
  4500. """
  4501. # add the tab if it was closed
  4502. self.ui.plot_tab_area.addTab(self.ui.preferences_tab, _("Preferences"))
  4503. # delete the absolute and relative position and messages in the infobar
  4504. # self.ui.position_label.setText("")
  4505. # self.ui.rel_position_label.setText("")
  4506. # hide coordinates toolbars in the infobar while in DB
  4507. self.ui.coords_toolbar.hide()
  4508. self.ui.delta_coords_toolbar.hide()
  4509. # Switch plot_area to preferences page
  4510. self.ui.plot_tab_area.setCurrentWidget(self.ui.preferences_tab)
  4511. # self.ui.show()
  4512. self.ui.pref_status_label.setStyleSheet("""
  4513. QLabel
  4514. {
  4515. color: black;
  4516. background-color: lightseagreen;
  4517. }
  4518. """
  4519. )
  4520. # detect changes in the preferences
  4521. for idx in range(self.ui.pref_tab_area.count()):
  4522. for tb in self.ui.pref_tab_area.widget(idx).findChildren(QtCore.QObject):
  4523. try:
  4524. try:
  4525. tb.textEdited.disconnect(self.preferencesUiManager.on_preferences_edited)
  4526. except (TypeError, AttributeError):
  4527. pass
  4528. tb.textEdited.connect(self.preferencesUiManager.on_preferences_edited)
  4529. except AttributeError:
  4530. pass
  4531. try:
  4532. try:
  4533. tb.modificationChanged.disconnect(self.preferencesUiManager.on_preferences_edited)
  4534. except (TypeError, AttributeError):
  4535. pass
  4536. tb.modificationChanged.connect(self.preferencesUiManager.on_preferences_edited)
  4537. except AttributeError:
  4538. pass
  4539. try:
  4540. try:
  4541. tb.toggled.disconnect(self.preferencesUiManager.on_preferences_edited)
  4542. except (TypeError, AttributeError):
  4543. pass
  4544. tb.toggled.connect(self.preferencesUiManager.on_preferences_edited)
  4545. except AttributeError:
  4546. pass
  4547. try:
  4548. try:
  4549. tb.valueChanged.disconnect(self.preferencesUiManager.on_preferences_edited)
  4550. except (TypeError, AttributeError):
  4551. pass
  4552. tb.valueChanged.connect(self.preferencesUiManager.on_preferences_edited)
  4553. except AttributeError:
  4554. pass
  4555. try:
  4556. try:
  4557. tb.currentIndexChanged.disconnect(self.preferencesUiManager.on_preferences_edited)
  4558. except (TypeError, AttributeError):
  4559. pass
  4560. tb.currentIndexChanged.connect(self.preferencesUiManager.on_preferences_edited)
  4561. except AttributeError:
  4562. pass
  4563. def on_tools_database(self, source='app'):
  4564. """
  4565. Adds the Tools Database in a Tab in Plot Area.
  4566. :return:
  4567. """
  4568. for idx in range(self.ui.plot_tab_area.count()):
  4569. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  4570. # there can be only one instance of Tools Database at one time
  4571. return
  4572. if source == 'app':
  4573. self.tools_db_tab = ToolsDB2(
  4574. app=self,
  4575. parent=self.ui,
  4576. callback_on_edited=self.on_tools_db_edited,
  4577. callback_on_tool_request=self.on_geometry_tool_add_from_db_executed
  4578. )
  4579. elif source == 'ncc':
  4580. self.tools_db_tab = ToolsDB2(
  4581. app=self,
  4582. parent=self.ui,
  4583. callback_on_edited=self.on_tools_db_edited,
  4584. callback_on_tool_request=self.ncclear_tool.on_ncc_tool_add_from_db_executed
  4585. )
  4586. elif source == 'paint':
  4587. self.tools_db_tab = ToolsDB2(
  4588. app=self,
  4589. parent=self.ui,
  4590. callback_on_edited=self.on_tools_db_edited,
  4591. callback_on_tool_request=self.paint_tool.on_paint_tool_add_from_db_executed
  4592. )
  4593. elif source == 'iso':
  4594. self.tools_db_tab = ToolsDB2(
  4595. app=self,
  4596. parent=self.ui,
  4597. callback_on_edited=self.on_tools_db_edited,
  4598. callback_on_tool_request=self.isolation_tool.on_iso_tool_add_from_db_executed
  4599. )
  4600. elif source == 'cutout':
  4601. self.tools_db_tab = ToolsDB2(
  4602. app=self,
  4603. parent=self.ui,
  4604. callback_on_edited=self.on_tools_db_edited,
  4605. callback_on_tool_request=self.cutout_tool.on_cutout_tool_add_from_db_executed
  4606. )
  4607. # add the tab if it was closed
  4608. try:
  4609. self.ui.plot_tab_area.addTab(self.tools_db_tab, _("Tools Database"))
  4610. self.tools_db_tab.setObjectName("database_tab")
  4611. except Exception as e:
  4612. log.debug("App.on_tools_database() --> %s" % str(e))
  4613. return
  4614. # delete the absolute and relative position and messages in the infobar
  4615. # self.ui.position_label.setText("")
  4616. # self.ui.rel_position_label.setText("")
  4617. # hide coordinates toolbars in the infobar while in DB
  4618. self.ui.coords_toolbar.hide()
  4619. self.ui.delta_coords_toolbar.hide()
  4620. # Switch plot_area to preferences page
  4621. self.ui.plot_tab_area.setCurrentWidget(self.tools_db_tab)
  4622. # detect changes in the Tools in Tools DB, connect signals from table widget in tab
  4623. self.tools_db_tab.ui_connect()
  4624. def on_tools_db_edited(self):
  4625. """
  4626. Executed whenever a tool is edited in Tools Database.
  4627. Will color the text of the Tools Database tab to Red color.
  4628. :return:
  4629. """
  4630. self.inform[str, bool].emit('[WARNING_NOTCL] %s' % _("Tools in Tools Database edited but not saved."), False)
  4631. for idx in range(self.ui.plot_tab_area.count()):
  4632. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  4633. self.ui.plot_tab_area.tabBar.setTabTextColor(idx, QtGui.QColor('red'))
  4634. self.tools_db_tab.ui.save_db_btn.setStyleSheet("QPushButton {color: red;}")
  4635. self.tools_db_changed_flag = True
  4636. def on_geometry_tool_add_from_db_executed(self, tool):
  4637. """
  4638. Here add the tool from DB in the selected geometry object.
  4639. :return:
  4640. """
  4641. tool_from_db = deepcopy(tool)
  4642. obj = self.collection.get_active()
  4643. if obj.kind == 'geometry':
  4644. obj.on_tool_from_db_inserted(tool=tool_from_db)
  4645. # close the tab and delete it
  4646. for idx in range(self.ui.plot_tab_area.count()):
  4647. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  4648. wdg = self.ui.plot_tab_area.widget(idx)
  4649. wdg.deleteLater()
  4650. self.ui.plot_tab_area.removeTab(idx)
  4651. self.inform.emit('[success] %s' % _("Tool from DB added in Tool Table."))
  4652. elif obj.kind == 'gerber':
  4653. self.isolation_tool.on_tool_from_db_inserted(tool=tool_from_db)
  4654. # close the tab and delete it
  4655. for idx in range(self.ui.plot_tab_area.count()):
  4656. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  4657. wdg = self.ui.plot_tab_area.widget(idx)
  4658. wdg.deleteLater()
  4659. self.ui.plot_tab_area.removeTab(idx)
  4660. self.inform.emit('[success] %s' % _("Tool from DB added in Tool Table."))
  4661. else:
  4662. self.inform.emit('[ERROR_NOTCL] %s' % _("Adding tool from DB is not allowed for this object."))
  4663. def on_plot_area_tab_closed(self, tab_obj_name):
  4664. """
  4665. Executed whenever a QTab is closed in the Plot Area.
  4666. :param tab_obj_name: The objectName of the Tab that was closed. This objectName is assigned on Tab creation
  4667. :return:
  4668. """
  4669. if tab_obj_name == "preferences_tab":
  4670. self.preferencesUiManager.on_close_preferences_tab()
  4671. elif tab_obj_name == "database_tab":
  4672. # disconnect the signals from the table widget in tab
  4673. self.tools_db_tab.ui_disconnect()
  4674. if self.tools_db_changed_flag is True:
  4675. msgbox = QtWidgets.QMessageBox()
  4676. msgbox.setText(_("One or more Tools are edited.\n"
  4677. "Do you want to update the Tools Database?"))
  4678. msgbox.setWindowTitle(_("Save Tools Database"))
  4679. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  4680. msgbox.setIcon(QtWidgets.QMessageBox.Question)
  4681. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  4682. msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  4683. msgbox.setDefaultButton(bt_yes)
  4684. msgbox.exec_()
  4685. response = msgbox.clickedButton()
  4686. if response == bt_yes:
  4687. self.tools_db_tab.on_save_tools_db()
  4688. self.inform.emit('[success] %s' % "Tools DB saved to file.")
  4689. else:
  4690. self.tools_db_changed_flag = False
  4691. self.inform.emit('')
  4692. return
  4693. self.tools_db_tab.deleteLater()
  4694. elif tab_obj_name == "text_editor_tab":
  4695. self.toggle_codeeditor = False
  4696. elif tab_obj_name == "bookmarks_tab":
  4697. self.book_dialog_tab.rebuild_actions()
  4698. self.book_dialog_tab.deleteLater()
  4699. else:
  4700. pass
  4701. # restore the coords toolbars
  4702. self.ui.toggle_coords(checked=self.defaults["global_coords_show"])
  4703. self.ui.toggle_delta_coords(checked=self.defaults["global_delta_coords_show"])
  4704. def on_flipy(self):
  4705. """
  4706. Executed when the menu entry in Options -> Flip on Y axis is clicked.
  4707. :return:
  4708. """
  4709. self.defaults.report_usage("on_flipy()")
  4710. obj_list = self.collection.get_selected()
  4711. xminlist = []
  4712. yminlist = []
  4713. xmaxlist = []
  4714. ymaxlist = []
  4715. if not obj_list:
  4716. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected to Flip on Y axis."))
  4717. else:
  4718. try:
  4719. # first get a bounding box to fit all
  4720. for obj in obj_list:
  4721. xmin, ymin, xmax, ymax = obj.bounds()
  4722. xminlist.append(xmin)
  4723. yminlist.append(ymin)
  4724. xmaxlist.append(xmax)
  4725. ymaxlist.append(ymax)
  4726. # get the minimum x,y and maximum x,y for all objects selected
  4727. xminimal = min(xminlist)
  4728. yminimal = min(yminlist)
  4729. xmaximal = max(xmaxlist)
  4730. ymaximal = max(ymaxlist)
  4731. px = 0.5 * (xminimal + xmaximal)
  4732. py = 0.5 * (yminimal + ymaximal)
  4733. # execute mirroring
  4734. for obj in obj_list:
  4735. obj.mirror('X', [px, py])
  4736. obj.plot()
  4737. self.app_obj.object_changed.emit(obj)
  4738. self.inform.emit('[success] %s' %
  4739. _("Flip on Y axis done."))
  4740. except Exception as e:
  4741. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Flip action was not executed."), str(e)))
  4742. return
  4743. def on_flipx(self):
  4744. """
  4745. Executed when the menu entry in Options -> Flip on X axis is clicked.
  4746. :return:
  4747. """
  4748. self.defaults.report_usage("on_flipx()")
  4749. obj_list = self.collection.get_selected()
  4750. xminlist = []
  4751. yminlist = []
  4752. xmaxlist = []
  4753. ymaxlist = []
  4754. if not obj_list:
  4755. self.inform.emit('[WARNING_NOTCL] %s' %
  4756. _("No object selected to Flip on X axis."))
  4757. else:
  4758. try:
  4759. # first get a bounding box to fit all
  4760. for obj in obj_list:
  4761. xmin, ymin, xmax, ymax = obj.bounds()
  4762. xminlist.append(xmin)
  4763. yminlist.append(ymin)
  4764. xmaxlist.append(xmax)
  4765. ymaxlist.append(ymax)
  4766. # get the minimum x,y and maximum x,y for all objects selected
  4767. xminimal = min(xminlist)
  4768. yminimal = min(yminlist)
  4769. xmaximal = max(xmaxlist)
  4770. ymaximal = max(ymaxlist)
  4771. px = 0.5 * (xminimal + xmaximal)
  4772. py = 0.5 * (yminimal + ymaximal)
  4773. # execute mirroring
  4774. for obj in obj_list:
  4775. obj.mirror('Y', [px, py])
  4776. obj.plot()
  4777. self.app_obj.object_changed.emit(obj)
  4778. self.inform.emit('[success] %s' %
  4779. _("Flip on X axis done."))
  4780. except Exception as e:
  4781. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Flip action was not executed."), str(e)))
  4782. return
  4783. def on_rotate(self, silent=False, preset=None):
  4784. """
  4785. Executed when Options -> Rotate Selection menu entry is clicked.
  4786. :param silent: If silent is True then use the preset value for the angle of the rotation.
  4787. :param preset: A value to be used as predefined angle for rotation.
  4788. :return:
  4789. """
  4790. self.defaults.report_usage("on_rotate()")
  4791. obj_list = self.collection.get_selected()
  4792. xminlist = []
  4793. yminlist = []
  4794. xmaxlist = []
  4795. ymaxlist = []
  4796. if not obj_list:
  4797. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected to Rotate."))
  4798. else:
  4799. if silent is False:
  4800. rotatebox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  4801. min=-360, max=360, decimals=4,
  4802. init_val=float(self.defaults['tools_transform_rotate']))
  4803. num, ok = rotatebox.get_value()
  4804. else:
  4805. num = preset
  4806. ok = True
  4807. if ok:
  4808. try:
  4809. # first get a bounding box to fit all
  4810. for obj in obj_list:
  4811. xmin, ymin, xmax, ymax = obj.bounds()
  4812. xminlist.append(xmin)
  4813. yminlist.append(ymin)
  4814. xmaxlist.append(xmax)
  4815. ymaxlist.append(ymax)
  4816. # get the minimum x,y and maximum x,y for all objects selected
  4817. xminimal = min(xminlist)
  4818. yminimal = min(yminlist)
  4819. xmaximal = max(xmaxlist)
  4820. ymaximal = max(ymaxlist)
  4821. px = 0.5 * (xminimal + xmaximal)
  4822. py = 0.5 * (yminimal + ymaximal)
  4823. for sel_obj in obj_list:
  4824. sel_obj.rotate(-float(num), point=(px, py))
  4825. sel_obj.plot()
  4826. self.app_obj.object_changed.emit(sel_obj)
  4827. self.inform.emit('[success] %s' % _("Rotation done."))
  4828. except Exception as e:
  4829. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Rotation movement was not executed."), str(e)))
  4830. return
  4831. def on_skewx(self):
  4832. """
  4833. Executed when the menu entry in Options -> Skew on X axis is clicked.
  4834. :return:
  4835. """
  4836. self.defaults.report_usage("on_skewx()")
  4837. obj_list = self.collection.get_selected()
  4838. xminlist = []
  4839. yminlist = []
  4840. if not obj_list:
  4841. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected to Skew/Shear on X axis."))
  4842. else:
  4843. skewxbox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  4844. min=-360, max=360, decimals=4,
  4845. init_val=float(self.defaults['tools_transform_skew_x']))
  4846. num, ok = skewxbox.get_value()
  4847. if ok:
  4848. # first get a bounding box to fit all
  4849. for obj in obj_list:
  4850. xmin, ymin, xmax, ymax = obj.bounds()
  4851. xminlist.append(xmin)
  4852. yminlist.append(ymin)
  4853. # get the minimum x,y and maximum x,y for all objects selected
  4854. xminimal = min(xminlist)
  4855. yminimal = min(yminlist)
  4856. for obj in obj_list:
  4857. obj.skew(num, 0, point=(xminimal, yminimal))
  4858. obj.plot()
  4859. self.app_obj.object_changed.emit(obj)
  4860. self.inform.emit('[success] %s' % _("Skew on X axis done."))
  4861. def on_skewy(self):
  4862. """
  4863. Executed when the menu entry in Options -> Skew on Y axis is clicked.
  4864. :return:
  4865. """
  4866. self.defaults.report_usage("on_skewy()")
  4867. obj_list = self.collection.get_selected()
  4868. xminlist = []
  4869. yminlist = []
  4870. if not obj_list:
  4871. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected to Skew/Shear on Y axis."))
  4872. else:
  4873. skewybox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  4874. min=-360, max=360, decimals=4,
  4875. init_val=float(self.defaults['tools_transform_skew_y']))
  4876. num, ok = skewybox.get_value()
  4877. if ok:
  4878. # first get a bounding box to fit all
  4879. for obj in obj_list:
  4880. xmin, ymin, xmax, ymax = obj.bounds()
  4881. xminlist.append(xmin)
  4882. yminlist.append(ymin)
  4883. # get the minimum x,y and maximum x,y for all objects selected
  4884. xminimal = min(xminlist)
  4885. yminimal = min(yminlist)
  4886. for obj in obj_list:
  4887. obj.skew(0, num, point=(xminimal, yminimal))
  4888. obj.plot()
  4889. self.app_obj.object_changed.emit(obj)
  4890. self.inform.emit('[success] %s' % _("Skew on Y axis done."))
  4891. def on_plots_updated(self):
  4892. """
  4893. Callback used to report when the plots have changed.
  4894. Adjust axes and zooms to fit.
  4895. :return: None
  4896. """
  4897. if self.is_legacy is False:
  4898. self.plotcanvas.update()
  4899. else:
  4900. self.plotcanvas.auto_adjust_axes()
  4901. self.on_zoom_fit()
  4902. self.collection.update_view()
  4903. # self.inform.emit(_("Plots updated ..."))
  4904. def on_toolbar_replot(self):
  4905. """
  4906. Callback for toolbar button. Re-plots all objects.
  4907. :return: None
  4908. """
  4909. self.log.debug("on_toolbar_replot()")
  4910. try:
  4911. obj = self.collection.get_active()
  4912. if obj:
  4913. obj.read_form()
  4914. else:
  4915. self.on_zoom_fit()
  4916. except AttributeError as e:
  4917. log.debug("on_toolbar_replot() -> %s" % str(e))
  4918. pass
  4919. self.plot_all()
  4920. def grid_status(self):
  4921. return True if self.ui.grid_snap_btn.isChecked() else False
  4922. def populate_cmenu_grids(self):
  4923. units = self.defaults['units'].lower()
  4924. # for act in self.ui.cmenu_gridmenu.actions():
  4925. # act.triggered.disconnect()
  4926. self.ui.cmenu_gridmenu.clear()
  4927. sorted_list = sorted(self.defaults["global_grid_context_menu"][str(units)])
  4928. grid_toggle = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/grid32_menu.png'),
  4929. _("Grid On/Off"))
  4930. grid_toggle.setCheckable(True)
  4931. grid_toggle.setChecked(True) if self.grid_status() else grid_toggle.setChecked(False)
  4932. self.ui.cmenu_gridmenu.addSeparator()
  4933. for grid in sorted_list:
  4934. action = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/grid32_menu.png'),
  4935. "%s" % str(grid))
  4936. action.triggered.connect(self.set_grid)
  4937. self.ui.cmenu_gridmenu.addSeparator()
  4938. grid_add = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/plus32.png'),
  4939. _("Add"))
  4940. grid_delete = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/delete32.png'),
  4941. _("Delete"))
  4942. grid_add.triggered.connect(self.on_grid_add)
  4943. grid_delete.triggered.connect(self.on_grid_delete)
  4944. grid_toggle.triggered.connect(lambda: self.ui.grid_snap_btn.trigger())
  4945. def set_grid(self):
  4946. menu_action = self.sender()
  4947. assert isinstance(menu_action, QtWidgets.QAction), "Expected QAction got %s" % type(menu_action)
  4948. self.ui.grid_gap_x_entry.setText(menu_action.text())
  4949. self.ui.grid_gap_y_entry.setText(menu_action.text())
  4950. def on_grid_add(self):
  4951. # ## Current application units in lower Case
  4952. units = self.defaults['units'].lower()
  4953. grid_add_popup = FCInputDialog(title=_("New Grid ..."),
  4954. text=_('Enter a Grid Value:'),
  4955. min=0.0000, max=99.9999, decimals=4)
  4956. grid_add_popup.setWindowIcon(QtGui.QIcon(self.resource_location + '/plus32.png'))
  4957. val, ok = grid_add_popup.get_value()
  4958. if ok:
  4959. if float(val) == 0:
  4960. self.inform.emit('[WARNING_NOTCL] %s' %
  4961. _("Please enter a grid value with non-zero value, in Float format."))
  4962. return
  4963. else:
  4964. if val not in self.defaults["global_grid_context_menu"][str(units)]:
  4965. self.defaults["global_grid_context_menu"][str(units)].append(val)
  4966. self.inform.emit('[success] %s...' % _("New Grid added"))
  4967. else:
  4968. self.inform.emit('[WARNING_NOTCL] %s...' % _("Grid already exists"))
  4969. else:
  4970. self.inform.emit('[WARNING_NOTCL] %s...' % _("Adding New Grid cancelled"))
  4971. def on_grid_delete(self):
  4972. # ## Current application units in lower Case
  4973. units = self.defaults['units'].lower()
  4974. grid_del_popup = FCInputDialog(title="Delete Grid ...",
  4975. text='Enter a Grid Value:',
  4976. min=0.0000, max=99.9999, decimals=4)
  4977. grid_del_popup.setWindowIcon(QtGui.QIcon(self.resource_location + '/delete32.png'))
  4978. val, ok = grid_del_popup.get_value()
  4979. if ok:
  4980. if float(val) == 0:
  4981. self.inform.emit('[WARNING_NOTCL] %s' %
  4982. _("Please enter a grid value with non-zero value, in Float format."))
  4983. return
  4984. else:
  4985. try:
  4986. self.defaults["global_grid_context_menu"][str(units)].remove(val)
  4987. except ValueError:
  4988. self.inform.emit('[ERROR_NOTCL]%s...' % _(" Grid Value does not exist"))
  4989. return
  4990. self.inform.emit('[success] %s...' % _("Grid Value deleted"))
  4991. else:
  4992. self.inform.emit('[WARNING_NOTCL] %s...' % _("Delete Grid value cancelled"))
  4993. def on_shortcut_list(self):
  4994. self.defaults.report_usage("on_shortcut_list()")
  4995. # add the tab if it was closed
  4996. self.ui.plot_tab_area.addTab(self.ui.shortcuts_tab, _("Key Shortcut List"))
  4997. # delete the absolute and relative position and messages in the infobar
  4998. # self.ui.position_label.setText("")
  4999. # self.ui.rel_position_label.setText("")
  5000. # hide coordinates toolbars in the infobar while in DB
  5001. self.ui.coords_toolbar.hide()
  5002. self.ui.delta_coords_toolbar.hide()
  5003. # Switch plot_area to preferences page
  5004. self.ui.plot_tab_area.setCurrentWidget(self.ui.shortcuts_tab)
  5005. # self.ui.show()
  5006. def on_select_tab(self, name):
  5007. # if the splitter is hidden, display it, else hide it but only if the current widget is the same
  5008. if self.ui.splitter.sizes()[0] == 0:
  5009. self.ui.splitter.setSizes([1, 1])
  5010. else:
  5011. if self.ui.notebook.currentWidget().objectName() == name + '_tab':
  5012. self.ui.splitter.setSizes([0, 1])
  5013. if name == 'project':
  5014. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  5015. elif name == 'selected':
  5016. self.ui.notebook.setCurrentWidget(self.ui.properties_tab)
  5017. elif name == 'tool':
  5018. self.ui.notebook.setCurrentWidget(self.ui.tool_tab)
  5019. def on_copy_name(self):
  5020. self.defaults.report_usage("on_copy_name()")
  5021. obj = self.collection.get_active()
  5022. try:
  5023. name = obj.options["name"]
  5024. except AttributeError:
  5025. log.debug("on_copy_name() --> No object selected to copy it's name")
  5026. self.inform.emit('[WARNING_NOTCL] %s' %
  5027. _(" No object selected to copy it's name"))
  5028. return
  5029. self.clipboard.setText(name)
  5030. self.inform.emit(_("Name copied on clipboard ..."))
  5031. def on_mouse_click_over_plot(self, event):
  5032. """
  5033. Default actions are:
  5034. :param event: Contains information about the event, like which button
  5035. was clicked, the pixel coordinates and the axes coordinates.
  5036. :return: None
  5037. """
  5038. self.pos = []
  5039. if self.is_legacy is False:
  5040. event_pos = event.pos
  5041. # pan_button = 2 if self.defaults["global_pan_button"] == '2'else 3
  5042. # # Set the mouse button for panning
  5043. # self.plotcanvas.view.camera.pan_button_setting = pan_button
  5044. else:
  5045. event_pos = (event.xdata, event.ydata)
  5046. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  5047. # pan_button = 3 if self.defaults["global_pan_button"] == '2' else 2
  5048. # So it can receive key presses
  5049. self.plotcanvas.native.setFocus()
  5050. self.pos_canvas = self.plotcanvas.translate_coords(event_pos)
  5051. if self.grid_status():
  5052. self.pos = self.geo_editor.snap(self.pos_canvas[0], self.pos_canvas[1])
  5053. else:
  5054. self.pos = (self.pos_canvas[0], self.pos_canvas[1])
  5055. try:
  5056. if event.button == 1:
  5057. # Reset here the relative coordinates so there is a new reference on the click position
  5058. if self.rel_point1 is None:
  5059. self.rel_point1 = self.pos
  5060. else:
  5061. self.rel_point2 = copy(self.rel_point1)
  5062. self.rel_point1 = self.pos
  5063. self.on_mouse_move_over_plot(event, origin_click=True)
  5064. except Exception as e:
  5065. App.log.debug("App.on_mouse_click_over_plot() --> Outside plot? --> %s" % str(e))
  5066. def on_mouse_double_click_over_plot(self, event):
  5067. if event.button == 1:
  5068. self.doubleclick = True
  5069. def on_mouse_move_over_plot(self, event, origin_click=None):
  5070. """
  5071. Callback for the mouse motion event over the plot.
  5072. :param event: Contains information about the event.
  5073. :param origin_click
  5074. :return: None
  5075. """
  5076. if self.is_legacy is False:
  5077. event_pos = event.pos
  5078. if self.defaults["global_pan_button"] == '2':
  5079. pan_button = 2
  5080. else:
  5081. pan_button = 3
  5082. self.event_is_dragging = event.is_dragging
  5083. else:
  5084. event_pos = (event.xdata, event.ydata)
  5085. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  5086. if self.defaults["global_pan_button"] == '2':
  5087. pan_button = 3
  5088. else:
  5089. pan_button = 2
  5090. self.event_is_dragging = self.plotcanvas.is_dragging
  5091. # So it can receive key presses but not when the Tcl Shell is active
  5092. if not self.ui.shell_dock.isVisible():
  5093. if not self.plotcanvas.native.hasFocus():
  5094. self.plotcanvas.native.setFocus()
  5095. self.pos_jump = event_pos
  5096. self.ui.popMenu.mouse_is_panning = False
  5097. if origin_click is None:
  5098. # if the RMB is clicked and mouse is moving over plot then 'panning_action' is True
  5099. if event.button == pan_button and self.event_is_dragging == 1:
  5100. # if a popup menu is active don't change mouse_is_panning variable because is not True
  5101. if self.ui.popMenu.popup_active:
  5102. self.ui.popMenu.popup_active = False
  5103. return
  5104. self.ui.popMenu.mouse_is_panning = True
  5105. return
  5106. if self.rel_point1 is not None:
  5107. try: # May fail in case mouse not within axes
  5108. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  5109. if pos_canvas[0] is None or pos_canvas[1] is None:
  5110. return
  5111. if self.grid_status():
  5112. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  5113. # Update cursor
  5114. self.app_cursor.set_data(np.asarray([(pos[0], pos[1])]),
  5115. symbol='++', edge_color=self.cursor_color_3D,
  5116. edge_width=self.defaults["global_cursor_width"],
  5117. size=self.defaults["global_cursor_size"])
  5118. else:
  5119. pos = (pos_canvas[0], pos_canvas[1])
  5120. self.dx = pos[0] - float(self.rel_point1[0])
  5121. self.dy = pos[1] - float(self.rel_point1[1])
  5122. self.ui.position_label.setText("&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  5123. "<b>Y</b>: %.4f&nbsp;" % (pos[0], pos[1]))
  5124. self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  5125. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (self.dx, self.dy))
  5126. units = self.defaults["units"].lower()
  5127. self.plotcanvas.text_hud.text = \
  5128. 'Dx:\t{:<.4f} [{:s}]\nDy:\t{:<.4f} [{:s}]\n\nX: \t{:<.4f} [{:s}]\nY: \t{:<.4f} [{:s}]'.format(
  5129. self.dx, units, self.dy, units, pos[0], units, pos[1], units)
  5130. self.mouse = [pos[0], pos[1]]
  5131. if self.defaults['global_selection_shape'] is False:
  5132. self.selection_type = None
  5133. return
  5134. # if the mouse is moved and the LMB is clicked then the action is a selection
  5135. if self.event_is_dragging == 1 and event.button == 1:
  5136. self.delete_selection_shape()
  5137. if self.dx < 0:
  5138. self.draw_moving_selection_shape(self.pos, pos, color=self.defaults['global_alt_sel_line'],
  5139. face_color=self.defaults['global_alt_sel_fill'])
  5140. self.selection_type = False
  5141. elif self.dx >= 0:
  5142. self.draw_moving_selection_shape(self.pos, pos)
  5143. self.selection_type = True
  5144. else:
  5145. self.selection_type = None
  5146. else:
  5147. self.selection_type = None
  5148. # hover effect - enabled in Preferences -> General -> appGUI Settings
  5149. if self.defaults['global_hover']:
  5150. for obj in self.collection.get_list():
  5151. try:
  5152. # select the object(s) only if it is enabled (plotted)
  5153. if obj.options['plot']:
  5154. if obj not in self.collection.get_selected():
  5155. poly_obj = Polygon(
  5156. [(obj.options['xmin'], obj.options['ymin']),
  5157. (obj.options['xmax'], obj.options['ymin']),
  5158. (obj.options['xmax'], obj.options['ymax']),
  5159. (obj.options['xmin'], obj.options['ymax'])]
  5160. )
  5161. if Point(pos).within(poly_obj):
  5162. if obj.isHovering is False:
  5163. obj.isHovering = True
  5164. obj.notHovering = True
  5165. # create the selection box around the selected object
  5166. self.draw_hover_shape(obj, color='#d1e0e0FF')
  5167. else:
  5168. if obj.notHovering is True:
  5169. obj.notHovering = False
  5170. obj.isHovering = False
  5171. self.delete_hover_shape()
  5172. except Exception:
  5173. # the Exception here will happen if we try to select on screen and we have an
  5174. # newly (and empty) just created Geometry or Excellon object that do not have the
  5175. # xmin, xmax, ymin, ymax options.
  5176. # In this case poly_obj creation (see above) will fail
  5177. pass
  5178. except Exception as e:
  5179. log.debug("App.on_mouse_move_over_plot() - rel_point1 is not None -> %s" % str(e))
  5180. self.ui.position_label.setText("")
  5181. self.ui.rel_position_label.setText("")
  5182. self.mouse = None
  5183. def on_mouse_click_release_over_plot(self, event):
  5184. """
  5185. Callback for the mouse click release over plot. This event is generated by the Matplotlib backend
  5186. and has been registered in ''self.__init__()''.
  5187. :param event: contains information about the event.
  5188. :return:
  5189. """
  5190. if self.is_legacy is False:
  5191. event_pos = event.pos
  5192. right_button = 2
  5193. else:
  5194. event_pos = (event.xdata, event.ydata)
  5195. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  5196. right_button = 3
  5197. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  5198. if self.grid_status():
  5199. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  5200. else:
  5201. pos = (pos_canvas[0], pos_canvas[1])
  5202. # if the released mouse button was RMB then test if it was a panning motion or not, if not it was a context
  5203. # canvas menu
  5204. if event.button == right_button and self.ui.popMenu.mouse_is_panning is False: # right click
  5205. self.ui.popMenu.mouse_is_panning = False
  5206. self.cursor = QtGui.QCursor()
  5207. self.populate_cmenu_grids()
  5208. self.ui.popMenu.popup(self.cursor.pos())
  5209. # if the released mouse button was LMB then test if we had a right-to-left selection or a left-to-right
  5210. # selection and then select a type of selection ("enclosing" or "touching")
  5211. if event.button == 1: # left click
  5212. modifiers = QtWidgets.QApplication.keyboardModifiers()
  5213. # If the SHIFT key is pressed when LMB is clicked then the coordinates are copied to clipboard
  5214. if modifiers == QtCore.Qt.ShiftModifier:
  5215. # do not auto open the Project Tab
  5216. self.click_noproject = True
  5217. self.clipboard.setText(
  5218. self.defaults["global_point_clipboard_format"] %
  5219. (self.decimals, self.pos[0], self.decimals, self.pos[1])
  5220. )
  5221. self.inform.emit('[success] %s' % _("Coordinates copied to clipboard."))
  5222. return
  5223. if self.doubleclick is True:
  5224. self.doubleclick = False
  5225. if self.collection.get_selected():
  5226. self.ui.notebook.setCurrentWidget(self.ui.properties_tab)
  5227. if self.ui.splitter.sizes()[0] == 0:
  5228. self.ui.splitter.setSizes([1, 1])
  5229. try:
  5230. # delete the selection shape(S) as it may be in the way
  5231. self.delete_selection_shape()
  5232. self.delete_hover_shape()
  5233. except Exception as e:
  5234. log.warning("FlatCAMApp.on_mouse_click_release_over_plot() double click --> Error: %s" % str(e))
  5235. return
  5236. else:
  5237. # WORKAROUND for LEGACY MODE
  5238. if self.is_legacy is True:
  5239. # if there is no move on canvas then we have no dragging selection
  5240. if self.dx == 0 or self.dy == 0:
  5241. self.selection_type = None
  5242. if self.selection_type is not None:
  5243. try:
  5244. self.selection_area_handler(self.pos, pos, self.selection_type)
  5245. self.selection_type = None
  5246. except Exception as e:
  5247. log.warning("FlatCAMApp.on_mouse_click_release_over_plot() select area --> Error: %s" % str(e))
  5248. return
  5249. else:
  5250. key_modifier = QtWidgets.QApplication.keyboardModifiers()
  5251. if key_modifier == QtCore.Qt.ShiftModifier:
  5252. mod_key = 'Shift'
  5253. elif key_modifier == QtCore.Qt.ControlModifier:
  5254. mod_key = 'Control'
  5255. else:
  5256. mod_key = None
  5257. try:
  5258. if self.command_active is None:
  5259. # If the CTRL key is pressed when the LMB is clicked then if the object is selected it will
  5260. # deselect, and if it's not selected then it will be selected
  5261. # If there is no active command (self.command_active is None) then we check if we clicked
  5262. # on a object by checking the bounding limits against mouse click position
  5263. if mod_key == self.defaults["global_mselect_key"]:
  5264. self.select_objects(key='multisel')
  5265. else:
  5266. # If there is no active command (self.command_active is None) then we check if
  5267. # we clicked on a object by checking the bounding limits against mouse click position
  5268. self.select_objects()
  5269. self.delete_hover_shape()
  5270. except Exception as e:
  5271. log.warning("FlatCAMApp.on_mouse_click_release_over_plot() select click --> Error: %s" % str(e))
  5272. return
  5273. def selection_area_handler(self, start_pos, end_pos, sel_type):
  5274. """
  5275. :param start_pos: mouse position when the selection LMB click was done
  5276. :param end_pos: mouse position when the left mouse button is released
  5277. :param sel_type: if True it's a left to right selection (enclosure), if False it's a 'touch' selection
  5278. :return:
  5279. """
  5280. poly_selection = Polygon([start_pos, (end_pos[0], start_pos[1]), end_pos, (start_pos[0], end_pos[1])])
  5281. # delete previous selection shape
  5282. self.delete_selection_shape()
  5283. # make all objects inactive
  5284. self.collection.set_all_inactive()
  5285. for obj in self.collection.get_list():
  5286. try:
  5287. # select the object(s) only if it is enabled (plotted)
  5288. if obj.options['plot']:
  5289. # it's a line without area
  5290. if obj.options['xmin'] == obj.options['xmax'] or obj.options['ymin'] == obj.options['ymax']:
  5291. poly_obj = unary_union(obj.solid_geometry).buffer(0.001)
  5292. # it's a geometry with area
  5293. else:
  5294. poly_obj = Polygon([(obj.options['xmin'], obj.options['ymin']),
  5295. (obj.options['xmax'], obj.options['ymin']),
  5296. (obj.options['xmax'], obj.options['ymax']),
  5297. (obj.options['xmin'], obj.options['ymax'])])
  5298. if poly_obj.is_empty or not poly_obj.is_valid:
  5299. continue
  5300. if sel_type is True:
  5301. if poly_obj.within(poly_selection):
  5302. # create the selection box around the selected object
  5303. if self.defaults['global_selection_shape'] is True:
  5304. self.draw_selection_shape(obj)
  5305. self.collection.set_active(obj.options['name'])
  5306. else:
  5307. if poly_selection.intersects(poly_obj):
  5308. # create the selection box around the selected object
  5309. if self.defaults['global_selection_shape'] is True:
  5310. self.draw_selection_shape(obj)
  5311. self.collection.set_active(obj.options['name'])
  5312. obj.selection_shape_drawn = True
  5313. except Exception as e:
  5314. # the Exception here will happen if we try to select on screen and we have an newly (and empty)
  5315. # just created Geometry or Excellon object that do not have the xmin, xmax, ymin, ymax options.
  5316. # In this case poly_obj creation (see above) will fail
  5317. log.debug("App.selection_area_handler() --> %s" % str(e))
  5318. def select_objects(self, key=None):
  5319. """
  5320. Will select objects clicked on canvas
  5321. :param key: for future use in cumulative selection
  5322. :return:
  5323. """
  5324. # list where we store the overlapped objects under our mouse left click position
  5325. if key is None:
  5326. self.objects_under_the_click_list = []
  5327. # Populate the list with the overlapped objects on the click position
  5328. curr_x, curr_y = self.pos
  5329. for obj in self.all_objects_list:
  5330. # ScriptObject and DocumentObject objects can't be selected
  5331. if obj.kind == 'script' or obj.kind == 'document':
  5332. continue
  5333. if key == 'multisel' and obj.options['name'] in self.objects_under_the_click_list:
  5334. continue
  5335. if (curr_x >= obj.options['xmin']) and (curr_x <= obj.options['xmax']) and \
  5336. (curr_y >= obj.options['ymin']) and (curr_y <= obj.options['ymax']):
  5337. if obj.options['name'] not in self.objects_under_the_click_list:
  5338. if obj.options['plot']:
  5339. # add objects to the objects_under_the_click list only if the object is plotted
  5340. # (active and not disabled)
  5341. self.objects_under_the_click_list.append(obj.options['name'])
  5342. try:
  5343. if self.objects_under_the_click_list:
  5344. curr_sel_obj = self.collection.get_active()
  5345. # case when there is only an object under the click and we toggle it
  5346. if len(self.objects_under_the_click_list) == 1:
  5347. if curr_sel_obj is None:
  5348. self.collection.set_active(self.objects_under_the_click_list[0])
  5349. curr_sel_obj = self.collection.get_active()
  5350. # create the selection box around the selected object
  5351. if self.defaults['global_selection_shape'] is True:
  5352. self.draw_selection_shape(curr_sel_obj)
  5353. curr_sel_obj.selection_shape_drawn = True
  5354. elif curr_sel_obj.options['name'] not in self.objects_under_the_click_list:
  5355. self.collection.on_objects_selection(False)
  5356. self.delete_selection_shape()
  5357. curr_sel_obj.selection_shape_drawn = False
  5358. self.collection.set_active(self.objects_under_the_click_list[0])
  5359. curr_sel_obj = self.collection.get_active()
  5360. # create the selection box around the selected object
  5361. if self.defaults['global_selection_shape'] is True:
  5362. self.draw_selection_shape(curr_sel_obj)
  5363. curr_sel_obj.selection_shape_drawn = True
  5364. self.selected_message(curr_sel_obj=curr_sel_obj)
  5365. elif curr_sel_obj.selection_shape_drawn is False:
  5366. if self.defaults['global_selection_shape'] is True:
  5367. self.draw_selection_shape(curr_sel_obj)
  5368. curr_sel_obj.selection_shape_drawn = True
  5369. else:
  5370. self.collection.on_objects_selection(False)
  5371. self.delete_selection_shape()
  5372. if self.call_source != 'app':
  5373. self.call_source = 'app'
  5374. self.selected_message(curr_sel_obj=curr_sel_obj)
  5375. else:
  5376. # If there is no selected object
  5377. # make active the first element of the overlapped objects list
  5378. if self.collection.get_active() is None:
  5379. self.collection.set_active(self.objects_under_the_click_list[0])
  5380. self.collection.get_by_name(self.objects_under_the_click_list[0]).selection_shape_drawn = True
  5381. name_sel_obj = self.collection.get_active().options['name']
  5382. # In case that there is a selected object but it is not in the overlapped object list
  5383. # make that object inactive and activate the first element in the overlapped object list
  5384. if name_sel_obj not in self.objects_under_the_click_list:
  5385. self.collection.set_inactive(name_sel_obj)
  5386. name_sel_obj = self.objects_under_the_click_list[0]
  5387. self.collection.set_active(name_sel_obj)
  5388. else:
  5389. sel_idx = self.objects_under_the_click_list.index(name_sel_obj)
  5390. self.collection.set_all_inactive()
  5391. self.collection.set_active(
  5392. self.objects_under_the_click_list[(sel_idx + 1) % len(self.objects_under_the_click_list)])
  5393. curr_sel_obj = self.collection.get_active()
  5394. # delete the possible selection box around a possible selected object
  5395. self.delete_selection_shape()
  5396. curr_sel_obj.selection_shape_drawn = False
  5397. # create the selection box around the selected object
  5398. if self.defaults['global_selection_shape'] is True:
  5399. self.draw_selection_shape(curr_sel_obj)
  5400. curr_sel_obj.selection_shape_drawn = True
  5401. self.selected_message(curr_sel_obj=curr_sel_obj)
  5402. else:
  5403. # deselect everything
  5404. self.collection.on_objects_selection(False)
  5405. # delete the possible selection box around a possible selected object
  5406. self.delete_selection_shape()
  5407. for o in self.collection.get_list():
  5408. o.selection_shape_drawn = False
  5409. # and as a convenience move the focus to the Project tab because Selected tab is now empty but
  5410. # only when working on App
  5411. if self.call_source == 'app':
  5412. if self.click_noproject is False:
  5413. # if the Tool Tab is in focus don't change focus to Project Tab
  5414. if not self.ui.notebook.currentWidget() is self.ui.tool_tab:
  5415. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  5416. else:
  5417. # restore auto open the Project Tab
  5418. self.click_noproject = False
  5419. # delete any text in the status bar, implicitly the last object name that was selected
  5420. # self.inform.emit("")
  5421. else:
  5422. self.call_source = 'app'
  5423. except Exception as e:
  5424. log.error("[ERROR] Something went bad in App.select_objects(). %s" % str(e))
  5425. def selected_message(self, curr_sel_obj):
  5426. if curr_sel_obj:
  5427. if curr_sel_obj.kind == 'gerber':
  5428. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  5429. color='green',
  5430. name=str(curr_sel_obj.options['name']),
  5431. tx=_("selected"))
  5432. )
  5433. elif curr_sel_obj.kind == 'excellon':
  5434. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  5435. color='brown',
  5436. name=str(curr_sel_obj.options['name']),
  5437. tx=_("selected"))
  5438. )
  5439. elif curr_sel_obj.kind == 'cncjob':
  5440. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  5441. color='blue',
  5442. name=str(curr_sel_obj.options['name']),
  5443. tx=_("selected"))
  5444. )
  5445. elif curr_sel_obj.kind == 'geometry':
  5446. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  5447. color='red',
  5448. name=str(curr_sel_obj.options['name']),
  5449. tx=_("selected"))
  5450. )
  5451. def delete_hover_shape(self):
  5452. self.hover_shapes.clear()
  5453. self.hover_shapes.redraw()
  5454. def draw_hover_shape(self, sel_obj, color=None):
  5455. """
  5456. :param sel_obj: The object for which the hover shape must be drawn
  5457. :param color: The color of the hover shape
  5458. :return: None
  5459. """
  5460. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  5461. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  5462. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  5463. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  5464. hover_rect = Polygon([pt1, pt2, pt3, pt4])
  5465. if self.defaults['units'].upper() == 'MM':
  5466. hover_rect = hover_rect.buffer(-0.1)
  5467. hover_rect = hover_rect.buffer(0.2)
  5468. else:
  5469. hover_rect = hover_rect.buffer(-0.00393)
  5470. hover_rect = hover_rect.buffer(0.00787)
  5471. # if color:
  5472. # face = Color(color)
  5473. # face.alpha = 0.2
  5474. # outline = Color(color, alpha=0.8)
  5475. # else:
  5476. # face = Color(self.defaults['global_sel_fill'])
  5477. # face.alpha = 0.2
  5478. # outline = self.defaults['global_sel_line']
  5479. if color:
  5480. face = color[:-2] + str(hex(int(0.2 * 255)))[2:]
  5481. outline = color[:-2] + str(hex(int(0.8 * 255)))[2:]
  5482. else:
  5483. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.2 * 255)))[2:]
  5484. outline = self.defaults['global_sel_line']
  5485. self.hover_shapes.add(hover_rect, color=outline, face_color=face, update=True, layer=0, tolerance=None)
  5486. if self.is_legacy is True:
  5487. self.hover_shapes.redraw()
  5488. def delete_selection_shape(self):
  5489. self.move_tool.sel_shapes.clear()
  5490. self.move_tool.sel_shapes.redraw()
  5491. def draw_selection_shape(self, sel_obj, color=None):
  5492. """
  5493. Will draw a selection shape around the selected object.
  5494. :param sel_obj: The object for which the selection shape must be drawn
  5495. :param color: The color for the selection shape.
  5496. :return: None
  5497. """
  5498. if sel_obj is None:
  5499. return
  5500. # it's a line without area
  5501. if sel_obj.options['xmin'] == sel_obj.options['xmax'] or sel_obj.options['ymin'] == sel_obj.options['ymax']:
  5502. sel_rect = unary_union(sel_obj.solid_geometry).buffer(0.100001)
  5503. # it's a geometry with area
  5504. else:
  5505. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  5506. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  5507. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  5508. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  5509. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  5510. b_sel_rect = None
  5511. try:
  5512. if self.defaults['units'].upper() == 'MM':
  5513. b_sel_rect = sel_rect.buffer(-0.1)
  5514. b_sel_rect = b_sel_rect.buffer(0.2)
  5515. else:
  5516. b_sel_rect = sel_rect.buffer(-0.00393)
  5517. b_sel_rect = b_sel_rect.buffer(0.00787)
  5518. except Exception:
  5519. pass
  5520. if b_sel_rect.is_empty or not b_sel_rect.is_valid or b_sel_rect is None:
  5521. b_sel_rect = sel_rect
  5522. if color:
  5523. face = color[:-2] + str(hex(int(0.2 * 255)))[2:]
  5524. outline = color[:-2] + str(hex(int(0.8 * 255)))[2:]
  5525. else:
  5526. if self.is_legacy is False:
  5527. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.2 * 255)))[2:]
  5528. outline = self.defaults['global_sel_line'][:-2] + str(hex(int(0.8 * 255)))[2:]
  5529. else:
  5530. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.4 * 255)))[2:]
  5531. outline = self.defaults['global_sel_line'][:-2] + str(hex(int(1.0 * 255)))[2:]
  5532. self.sel_objects_list.append(self.move_tool.sel_shapes.add(b_sel_rect,
  5533. color=outline,
  5534. face_color=face,
  5535. update=True,
  5536. layer=0,
  5537. tolerance=None))
  5538. if self.is_legacy is True:
  5539. self.move_tool.sel_shapes.redraw()
  5540. def draw_moving_selection_shape(self, old_coords, coords, **kwargs):
  5541. """
  5542. Will draw a selection shape when dragging mouse on canvas.
  5543. :param old_coords: Old coordinates
  5544. :param coords: New coordinates
  5545. :param kwargs: Keyword arguments
  5546. :return:
  5547. """
  5548. if 'color' in kwargs:
  5549. color = kwargs['color']
  5550. else:
  5551. color = self.defaults['global_sel_line']
  5552. if 'face_color' in kwargs:
  5553. face_color = kwargs['face_color']
  5554. else:
  5555. face_color = self.defaults['global_sel_fill']
  5556. if 'face_alpha' in kwargs:
  5557. face_alpha = kwargs['face_alpha']
  5558. else:
  5559. face_alpha = 0.3
  5560. x0, y0 = old_coords
  5561. x1, y1 = coords
  5562. pt1 = (x0, y0)
  5563. pt2 = (x1, y0)
  5564. pt3 = (x1, y1)
  5565. pt4 = (x0, y1)
  5566. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  5567. # color_t = Color(face_color)
  5568. # color_t.alpha = face_alpha
  5569. color_t = face_color[:-2] + str(hex(int(face_alpha * 255)))[2:]
  5570. self.move_tool.sel_shapes.add(sel_rect, color=color, face_color=color_t, update=True,
  5571. layer=0, tolerance=None)
  5572. if self.is_legacy is True:
  5573. self.move_tool.sel_shapes.redraw()
  5574. def obj_properties(self):
  5575. """
  5576. Will launch the object Properties Tool
  5577. :return:
  5578. """
  5579. self.defaults.report_usage("obj_properties()")
  5580. self.properties_tool.run(toggle=False)
  5581. def on_project_context_save(self):
  5582. """
  5583. Wrapper, will save the object function of it's type
  5584. :return:
  5585. """
  5586. sel_objects = self.collection.get_selected()
  5587. len_objects = len(sel_objects)
  5588. cnt = 0
  5589. if len_objects > 1:
  5590. for o in sel_objects:
  5591. if o.kind == 'cncjob':
  5592. cnt += 1
  5593. if len_objects == cnt:
  5594. # all selected objects are of type CNCJOB therefore we issue a multiple save
  5595. _filter_ = self.defaults['cncjob_save_filters'] + \
  5596. ";;RML1 Files .rol (*.rol);;HPGL Files .plt (*.plt)"
  5597. dir_file_to_save = self.get_last_save_folder() + '/multi_save'
  5598. try:
  5599. filename, _f = FCFileSaveDialog.get_saved_filename(
  5600. caption=_("Export Code ..."),
  5601. directory=dir_file_to_save,
  5602. ext_filter=_filter_
  5603. )
  5604. except TypeError:
  5605. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export Code ..."),
  5606. ext_filter=_filter_)
  5607. filename = filename.rpartition('/')[0]
  5608. for ob in sel_objects:
  5609. ob.read_form()
  5610. fname = '%s/%s' % (filename, ob.options['name'])
  5611. ob.export_gcode_handler(fname, is_gcode=True)
  5612. return
  5613. obj = self.collection.get_active()
  5614. if type(obj) == GeometryObject:
  5615. self.on_file_exportdxf()
  5616. elif type(obj) == ExcellonObject:
  5617. self.on_file_saveexcellon()
  5618. elif type(obj) == CNCJobObject:
  5619. obj.on_exportgcode_button_click()
  5620. elif type(obj) == GerberObject:
  5621. self.on_file_savegerber()
  5622. elif type(obj) == ScriptObject:
  5623. self.on_file_savescript()
  5624. elif type(obj) == DocumentObject:
  5625. self.on_file_savedocument()
  5626. def obj_move(self):
  5627. """
  5628. Callback for the Move menu entry in various Context Menu's.
  5629. :return:
  5630. """
  5631. self.defaults.report_usage("obj_move()")
  5632. self.move_tool.run(toggle=False)
  5633. # ###############################################################################################################
  5634. # ### The following section has the functions that are displayed and call the Editor tab CNCJob Tab #############
  5635. # ###############################################################################################################
  5636. def init_code_editor(self, name):
  5637. self.text_editor_tab = AppTextEditor(app=self, plain_text=True)
  5638. # add the tab if it was closed
  5639. self.ui.plot_tab_area.addTab(self.text_editor_tab, '%s' % name)
  5640. self.text_editor_tab.setObjectName('text_editor_tab')
  5641. # delete the absolute and relative position and messages in the infobar
  5642. # self.ui.position_label.setText("")
  5643. # self.ui.rel_position_label.setText("")
  5644. # hide coordinates toolbars in the infobar while in DB
  5645. self.ui.coords_toolbar.hide()
  5646. self.ui.delta_coords_toolbar.hide()
  5647. self.toggle_codeeditor = True
  5648. self.text_editor_tab.code_editor.completer_enable = False
  5649. self.text_editor_tab.buttonRun.hide()
  5650. # make sure to keep a reference to the code editor
  5651. self.reference_code_editor = self.text_editor_tab.code_editor
  5652. # Switch plot_area to CNCJob tab
  5653. self.ui.plot_tab_area.setCurrentWidget(self.text_editor_tab)
  5654. def on_view_source(self):
  5655. """
  5656. Called when the user wants to see the source file of the selected object
  5657. :return:
  5658. """
  5659. try:
  5660. obj = self.collection.get_active()
  5661. except Exception as e:
  5662. log.debug("App.on_view_source() --> %s" % str(e))
  5663. self.inform.emit('[WARNING_NOTCL] %s' % _("Select an Gerber or Excellon file to view it's source file."))
  5664. return 'fail'
  5665. if obj is None:
  5666. self.inform.emit('[WARNING_NOTCL] %s' % _("Select an Gerber or Excellon file to view it's source file."))
  5667. return 'fail'
  5668. self.inform.emit('%s' % _("Viewing the source code of the selected object."))
  5669. self.proc_container.view.set_busy(_("Loading..."))
  5670. flt = "All Files (*.*)"
  5671. if obj.kind == 'gerber':
  5672. flt = "Gerber Files .gbr (*.GBR);;PDF Files .pdf (*.PDF);;All Files (*.*)"
  5673. elif obj.kind == 'excellon':
  5674. flt = "Excellon Files .drl (*.DRL);;PDF Files .pdf (*.PDF);;All Files (*.*)"
  5675. elif obj.kind == 'cncjob':
  5676. flt = "GCode Files .nc (*.NC);;PDF Files .pdf (*.PDF);;All Files (*.*)"
  5677. self.source_editor_tab = AppTextEditor(app=self, plain_text=True)
  5678. # add the tab if it was closed
  5679. self.ui.plot_tab_area.addTab(self.source_editor_tab, '%s' % _("Source Editor"))
  5680. self.source_editor_tab.setObjectName('source_editor_tab')
  5681. # delete the absolute and relative position and messages in the infobar
  5682. # self.ui.position_label.setText("")
  5683. # self.ui.rel_position_label.setText("")
  5684. # hide coordinates toolbars in the infobar while in DB
  5685. self.ui.coords_toolbar.hide()
  5686. self.ui.delta_coords_toolbar.hide()
  5687. self.source_editor_tab.code_editor.completer_enable = False
  5688. self.source_editor_tab.buttonRun.hide()
  5689. # Switch plot_area to CNCJob tab
  5690. self.ui.plot_tab_area.setCurrentWidget(self.source_editor_tab)
  5691. try:
  5692. self.source_editor_tab.buttonOpen.clicked.disconnect()
  5693. except TypeError:
  5694. pass
  5695. self.source_editor_tab.buttonOpen.clicked.connect(lambda: self.source_editor_tab.handleOpen(filt=flt))
  5696. try:
  5697. self.source_editor_tab.buttonSave.clicked.disconnect()
  5698. except TypeError:
  5699. pass
  5700. self.source_editor_tab.buttonSave.clicked.connect(lambda: self.source_editor_tab.handleSaveGCode(filt=flt))
  5701. # then append the text from GCode to the text editor
  5702. if obj.kind == 'cncjob':
  5703. try:
  5704. file = obj.export_gcode(to_file=True)
  5705. if file == 'fail':
  5706. return 'fail'
  5707. except AttributeError:
  5708. self.inform.emit('[WARNING_NOTCL] %s' %
  5709. _("There is no selected object for which to see it's source file code."))
  5710. return 'fail'
  5711. else:
  5712. try:
  5713. file = StringIO(obj.source_file)
  5714. except (AttributeError, TypeError):
  5715. self.inform.emit('[WARNING_NOTCL] %s' %
  5716. _("There is no selected object for which to see it's source file code."))
  5717. return 'fail'
  5718. self.source_editor_tab.t_frame.hide()
  5719. try:
  5720. self.source_editor_tab.load_text(file.getvalue(), clear_text=True, move_to_start=True)
  5721. except Exception as e:
  5722. log.debug('App.on_view_source() -->%s' % str(e))
  5723. self.inform.emit('[ERROR] %s: %s' % (_('Failed to load the source code for the selected object'), str(e)))
  5724. return
  5725. self.source_editor_tab.t_frame.show()
  5726. self.proc_container.view.set_idle()
  5727. # self.ui.show()
  5728. def on_toggle_code_editor(self):
  5729. self.defaults.report_usage("on_toggle_code_editor()")
  5730. if self.toggle_codeeditor is False:
  5731. self.init_code_editor(name=_("Code Editor"))
  5732. self.text_editor_tab.buttonOpen.clicked.disconnect()
  5733. self.text_editor_tab.buttonOpen.clicked.connect(self.text_editor_tab.handleOpen)
  5734. self.text_editor_tab.buttonSave.clicked.disconnect()
  5735. self.text_editor_tab.buttonSave.clicked.connect(self.text_editor_tab.handleSaveGCode)
  5736. else:
  5737. for idx in range(self.ui.plot_tab_area.count()):
  5738. if self.ui.plot_tab_area.widget(idx).objectName() == "text_editor_tab":
  5739. self.ui.plot_tab_area.closeTab(idx)
  5740. break
  5741. self.toggle_codeeditor = False
  5742. def on_code_editor_close(self):
  5743. self.toggle_codeeditor = False
  5744. def goto_text_line(self):
  5745. """
  5746. Will scroll a text to the specified text line.
  5747. :return: None
  5748. """
  5749. dia_box = Dialog_box(title=_("Go to Line ..."),
  5750. label=_("Line:"),
  5751. icon=QtGui.QIcon(self.resource_location + '/jump_to16.png'),
  5752. initial_text='')
  5753. try:
  5754. line = int(dia_box.location) - 1
  5755. except (ValueError, TypeError):
  5756. line = 0
  5757. if dia_box.ok:
  5758. # make sure to move first the cursor at the end so after finding the line the line will be positioned
  5759. # at the top of the window
  5760. self.ui.plot_tab_area.currentWidget().code_editor.moveCursor(QTextCursor.End)
  5761. # get the document() of the AppTextEditor
  5762. doc = self.ui.plot_tab_area.currentWidget().code_editor.document()
  5763. # create a Text Cursor based on the searched line
  5764. cursor = QTextCursor(doc.findBlockByLineNumber(line))
  5765. # set cursor of the code editor with the cursor at the searcehd line
  5766. self.ui.plot_tab_area.currentWidget().code_editor.setTextCursor(cursor)
  5767. def plot_all(self, fit_view=True, muted=False, use_thread=True):
  5768. """
  5769. Re-generates all plots from all objects.
  5770. :param fit_view: if True will plot the objects and will adjust the zoom to fit all plotted objects into view
  5771. :param muted: if True don't print messages
  5772. :param use_thread: if True will use threading for plotting the objects
  5773. :return: None
  5774. """
  5775. self.log.debug("Plot_all()")
  5776. if muted is not True:
  5777. self.inform[str, bool].emit('%s...' % _("Redrawing all objects"), False)
  5778. for plot_obj in self.collection.get_list():
  5779. def worker_task(obj):
  5780. with self.proc_container.new("Plotting"):
  5781. obj.plot(kind=self.defaults["cncjob_plot_kind"])
  5782. if fit_view is True:
  5783. self.app_obj.object_plotted.emit(obj)
  5784. if use_thread is True:
  5785. # Send to worker
  5786. self.worker_task.emit({'fcn': worker_task, 'params': [plot_obj]})
  5787. else:
  5788. worker_task(plot_obj)
  5789. def register_folder(self, filename):
  5790. """
  5791. Register the last folder used by the app to open something
  5792. :param filename: the last folder is extracted from the filename
  5793. :return: None
  5794. """
  5795. self.defaults["global_last_folder"] = os.path.split(str(filename))[0]
  5796. def register_save_folder(self, filename):
  5797. """
  5798. Register the last folder used by the app to save something
  5799. :param filename: the last folder is extracted from the filename
  5800. :return: None
  5801. """
  5802. self.defaults["global_last_save_folder"] = os.path.split(str(filename))[0]
  5803. # def set_progress_bar(self, percentage, text=""):
  5804. # """
  5805. # Set a progress bar to a value (percentage)
  5806. #
  5807. # :param percentage: Value set to the progressbar
  5808. # :param text: Not used
  5809. # :return: None
  5810. # """
  5811. # self.ui.progress_bar.setValue(int(percentage))
  5812. def setup_recent_items(self):
  5813. """
  5814. Setup a dictionary with the recent files accessed, organized by type
  5815. :return:
  5816. """
  5817. icons = {
  5818. "gerber": self.resource_location + "/flatcam_icon16.png",
  5819. "excellon": self.resource_location + "/drill16.png",
  5820. 'geometry': self.resource_location + "/geometry16.png",
  5821. "cncjob": self.resource_location + "/cnc16.png",
  5822. "script": self.resource_location + "/script_new24.png",
  5823. "document": self.resource_location + "/notes16_1.png",
  5824. "project": self.resource_location + "/project16.png",
  5825. "svg": self.resource_location + "/geometry16.png",
  5826. "dxf": self.resource_location + "/dxf16.png",
  5827. "pdf": self.resource_location + "/pdf32.png",
  5828. "image": self.resource_location + "/image16.png"
  5829. }
  5830. try:
  5831. image_opener = self.image_tool.import_image
  5832. except AttributeError:
  5833. image_opener = None
  5834. openers = {
  5835. 'gerber': lambda fname: self.worker_task.emit({'fcn': self.f_handlers.open_gerber, 'params': [fname]}),
  5836. 'excellon': lambda fname: self.worker_task.emit({'fcn': self.f_handlers.open_excellon, 'params': [fname]}),
  5837. 'geometry': lambda fname: self.worker_task.emit({'fcn': self.f_handlers.import_dxf, 'params': [fname]}),
  5838. 'cncjob': lambda fname: self.worker_task.emit({'fcn': self.f_handlers.open_gcode, 'params': [fname]}),
  5839. "script": lambda fname: self.worker_task.emit({'fcn': self.f_handlers.open_script, 'params': [fname]}),
  5840. "document": None,
  5841. 'project': self.f_handlers.open_project,
  5842. 'svg': self.f_handlers.import_svg,
  5843. 'dxf': self.f_handlers.import_dxf,
  5844. 'image': image_opener,
  5845. 'pdf': lambda fname: self.worker_task.emit({'fcn': self.pdf_tool.open_pdf, 'params': [fname]})
  5846. }
  5847. # Open recent file for files
  5848. try:
  5849. f = open(self.data_path + '/recent.json')
  5850. except IOError:
  5851. App.log.error("Failed to load recent item list.")
  5852. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to load recent item list."))
  5853. return
  5854. try:
  5855. self.recent = json.load(f)
  5856. except json.errors.JSONDecodeError:
  5857. App.log.error("Failed to parse recent item list.")
  5858. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to parse recent item list."))
  5859. f.close()
  5860. return
  5861. f.close()
  5862. # Open recent file for projects
  5863. try:
  5864. fp = open(self.data_path + '/recent_projects.json')
  5865. except IOError:
  5866. App.log.error("Failed to load recent project item list.")
  5867. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to load recent projects item list."))
  5868. return
  5869. try:
  5870. self.recent_projects = json.load(fp)
  5871. except json.errors.JSONDecodeError:
  5872. App.log.error("Failed to parse recent project item list.")
  5873. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to parse recent project item list."))
  5874. fp.close()
  5875. return
  5876. fp.close()
  5877. # Closure needed to create callbacks in a loop.
  5878. # Otherwise late binding occurs.
  5879. def make_callback(func, fname):
  5880. def opener():
  5881. func(fname)
  5882. return opener
  5883. def reset_recent_files():
  5884. # Reset menu
  5885. self.ui.recent.clear()
  5886. self.recent = []
  5887. try:
  5888. ff = open(self.data_path + '/recent.json', 'w')
  5889. except IOError:
  5890. App.log.error("Failed to open recent items file for writing.")
  5891. return
  5892. json.dump(self.recent, ff)
  5893. def reset_recent_projects():
  5894. # Reset menu
  5895. self.ui.recent_projects.clear()
  5896. self.recent_projects = []
  5897. try:
  5898. frp = open(self.data_path + '/recent_projects.json', 'w')
  5899. except IOError:
  5900. App.log.error("Failed to open recent projects items file for writing.")
  5901. return
  5902. json.dump(self.recent, frp)
  5903. # Reset menu
  5904. self.ui.recent.clear()
  5905. self.ui.recent_projects.clear()
  5906. # Create menu items for projects
  5907. for recent in self.recent_projects:
  5908. filename = recent['filename'].split('/')[-1].split('\\')[-1]
  5909. if recent['kind'] == 'project':
  5910. try:
  5911. action = QtWidgets.QAction(QtGui.QIcon(icons[recent["kind"]]), filename, self)
  5912. # Attach callback
  5913. o = make_callback(openers[recent["kind"]], recent['filename'])
  5914. action.triggered.connect(o)
  5915. self.ui.recent_projects.addAction(action)
  5916. except KeyError:
  5917. App.log.error("Unsupported file type: %s" % recent["kind"])
  5918. # Last action in Recent Files menu is one that Clear the content
  5919. clear_action_proj = QtWidgets.QAction(QtGui.QIcon(self.resource_location + '/trash32.png'),
  5920. (_("Clear Recent projects")), self)
  5921. clear_action_proj.triggered.connect(reset_recent_projects)
  5922. self.ui.recent_projects.addSeparator()
  5923. self.ui.recent_projects.addAction(clear_action_proj)
  5924. # Create menu items for files
  5925. for recent in self.recent:
  5926. filename = recent['filename'].split('/')[-1].split('\\')[-1]
  5927. if recent['kind'] != 'project':
  5928. try:
  5929. action = QtWidgets.QAction(QtGui.QIcon(icons[recent["kind"]]), filename, self)
  5930. # Attach callback
  5931. o = make_callback(openers[recent["kind"]], recent['filename'])
  5932. action.triggered.connect(o)
  5933. self.ui.recent.addAction(action)
  5934. except KeyError:
  5935. App.log.error("Unsupported file type: %s" % recent["kind"])
  5936. # Last action in Recent Files menu is one that Clear the content
  5937. clear_action = QtWidgets.QAction(QtGui.QIcon(self.resource_location + '/trash32.png'),
  5938. (_("Clear Recent files")), self)
  5939. clear_action.triggered.connect(reset_recent_files)
  5940. self.ui.recent.addSeparator()
  5941. self.ui.recent.addAction(clear_action)
  5942. # self.builder.get_object('open_recent').set_submenu(recent_menu)
  5943. # self.ui.menufilerecent.set_submenu(recent_menu)
  5944. # recent_menu.show_all()
  5945. # self.ui.recent.show()
  5946. self.log.debug("Recent items list has been populated.")
  5947. def on_properties_tab_click(self, index):
  5948. if self.ui.properties_scroll_area.widget().objectName() == 'default_properties':
  5949. self.setup_default_properties_tab()
  5950. def setup_default_properties_tab(self):
  5951. """
  5952. Default text for the Properties tab when is not taken by the Object UI.
  5953. :return:
  5954. """
  5955. # label = QtWidgets.QLabel("Choose an item from Project")
  5956. # label.setAlignment(QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter)
  5957. # sel_title = QtWidgets.QTextEdit()
  5958. # sel_title.setTextInteractionFlags(QtCore.Qt.NoTextInteraction)
  5959. # sel_title.setFrameStyle(QtWidgets.QFrame.NoFrame)
  5960. #
  5961. # f_settings = QSettings("Open Source", "FlatCAM")
  5962. # if f_settings.contains("notebook_font_size"):
  5963. # fsize = f_settings.value('notebook_font_size', type=int)
  5964. # else:
  5965. # fsize = 12
  5966. #
  5967. # tsize = fsize + int(fsize / 2)
  5968. #
  5969. # selected_text = ''
  5970. #
  5971. # sel_title.setText(selected_text)
  5972. # sel_title.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
  5973. # Tree Widget
  5974. d_properties_tw = FCTree(columns=2)
  5975. d_properties_tw.setObjectName("default_properties")
  5976. d_properties_tw.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
  5977. d_properties_tw.setStyleSheet("QTreeWidget {border: 0px;}")
  5978. root = d_properties_tw.invisibleRootItem()
  5979. font = QtGui.QFont()
  5980. font.setBold(True)
  5981. p_color = QtGui.QColor("#000000") if self.defaults['global_gray_icons'] is False else QtGui.QColor("#FFFFFF")
  5982. # main Items categories
  5983. general_cat = d_properties_tw.addParent(root, _('General'), expanded=True, color=p_color, font=font)
  5984. d_properties_tw.addChild(parent=general_cat,
  5985. title=['%s:' % _("Name"), '%s' % _("FlatCAM Evo")], column1=True)
  5986. d_properties_tw.addChild(parent=general_cat,
  5987. title=['%s:' % _("Version"), '%s' % str(self.version)], column1=True)
  5988. d_properties_tw.addChild(parent=general_cat,
  5989. title=['%s:' % _("Release date"), '%s' % str(self.version_date)], column1=True)
  5990. grid_cat = d_properties_tw.addParent(root, _('Grid'), expanded=True, color=p_color, font=font)
  5991. d_properties_tw.addChild(parent=grid_cat,
  5992. title=['%s:' % _("Displayed"), '%s' % str(self.defaults['global_grid_lines'])],
  5993. column1=True)
  5994. d_properties_tw.addChild(parent=grid_cat,
  5995. title=['%s:' % _("Snap"), '%s' % str(self.defaults['global_grid_snap'])],
  5996. column1=True)
  5997. d_properties_tw.addChild(parent=grid_cat,
  5998. title=['%s:' % _("X value"), '%s' % str(self.ui.grid_gap_x_entry.get_value())],
  5999. column1=True)
  6000. d_properties_tw.addChild(parent=grid_cat,
  6001. title=['%s:' % _("Y value"), '%s' % str(self.ui.grid_gap_y_entry.get_value())],
  6002. column1=True)
  6003. canvas_cat = d_properties_tw.addParent(root, _('Canvas'), expanded=True, color=p_color, font=font)
  6004. d_properties_tw.addChild(parent=canvas_cat,
  6005. title=['%s:' % _("Axis"), '%s' % str(self.defaults['global_axis'])],
  6006. column1=True)
  6007. d_properties_tw.addChild(parent=canvas_cat,
  6008. title=['%s:' % _("Workspace active"),
  6009. '%s' % str(self.defaults['global_workspace'])],
  6010. column1=True)
  6011. d_properties_tw.addChild(parent=canvas_cat,
  6012. title=['%s:' % _("Workspace size"),
  6013. '%s' % str(self.defaults['global_workspaceT'])],
  6014. column1=True)
  6015. d_properties_tw.addChild(parent=canvas_cat,
  6016. title=['%s:' % _("Workspace orientation"),
  6017. '%s' % _("Portrait") if self.defaults[
  6018. 'global_workspace_orientation'] == 'p' else
  6019. _("Landscape")],
  6020. column1=True)
  6021. d_properties_tw.addChild(parent=canvas_cat,
  6022. title=['%s:' % _("HUD"), '%s' % str(self.defaults['global_hud'])],
  6023. column1=True)
  6024. self.ui.properties_scroll_area.setWidget(d_properties_tw)
  6025. def setup_obj_classes(self):
  6026. """
  6027. Sets up application specifics on the FlatCAMObj class. This way the object.app attribute will point to the App
  6028. class.
  6029. :return: None
  6030. """
  6031. FlatCAMObj.app = self
  6032. ObjectCollection.app = self
  6033. Gerber.app = self
  6034. Excellon.app = self
  6035. Geometry.app = self
  6036. CNCjob.app = self
  6037. FCProcess.app = self
  6038. FCProcessContainer.app = self
  6039. OptionsGroupUI.app = self
  6040. def version_check(self):
  6041. """
  6042. Checks for the latest version of the program. Alerts the
  6043. user if theirs is outdated. This method is meant to be run
  6044. in a separate thread.
  6045. :return: None
  6046. """
  6047. self.log.debug("version_check()")
  6048. if self.ui.general_defaults_form.general_app_group.send_stats_cb.get_value() is True:
  6049. full_url = "%s?s=%s&v=%s&os=%s&%s" % (
  6050. App.version_url,
  6051. str(self.defaults['global_serial']),
  6052. str(self.version),
  6053. str(self.os),
  6054. urllib.parse.urlencode(self.defaults["global_stats"])
  6055. )
  6056. # full_url = App.version_url + "?s=" + str(self.defaults['global_serial']) + \
  6057. # "&v=" + str(self.version) + "&os=" + str(self.os) + "&" + \
  6058. # urllib.parse.urlencode(self.defaults["global_stats"])
  6059. else:
  6060. # no_stats dict; just so it won't break things on website
  6061. no_ststs_dict = {}
  6062. no_ststs_dict["global_ststs"] = {}
  6063. full_url = App.version_url + "?s=" + str(self.defaults['global_serial']) + "&v=" + str(self.version)
  6064. full_url += "&os=" + str(self.os) + "&" + urllib.parse.urlencode(no_ststs_dict["global_ststs"])
  6065. App.log.debug("Checking for updates @ %s" % full_url)
  6066. # ## Get the data
  6067. try:
  6068. f = urllib.request.urlopen(full_url)
  6069. except Exception:
  6070. # App.log.warning("Failed checking for latest version. Could not connect.")
  6071. self.log.warning("Failed checking for latest version. Could not connect.")
  6072. self.inform.emit('[WARNING_NOTCL] %s' % _("Failed checking for latest version. Could not connect."))
  6073. return
  6074. try:
  6075. data = json.load(f)
  6076. except Exception as e:
  6077. App.log.error("Could not parse information about latest version.")
  6078. self.inform.emit('[ERROR_NOTCL] %s' % _("Could not parse information about latest version."))
  6079. App.log.debug("json.load(): %s" % str(e))
  6080. f.close()
  6081. return
  6082. f.close()
  6083. # ## Latest version?
  6084. if self.version >= data["version"]:
  6085. App.log.debug("FlatCAM is up to date!")
  6086. self.inform.emit('[success] %s' % _("FlatCAM is up to date!"))
  6087. return
  6088. App.log.debug("Newer version available.")
  6089. self.message.emit(
  6090. _("Newer Version Available"),
  6091. '%s<br><br>><b>%s</b><br>%s' % (
  6092. _("There is a newer version of FlatCAM available for download:"),
  6093. str(data["name"]),
  6094. str(data["message"])
  6095. ),
  6096. _("info")
  6097. )
  6098. def on_plotcanvas_setup(self, container=None):
  6099. """
  6100. This is doing the setup for the plot area (canvas).
  6101. :param container: QT Widget where to install the canvas
  6102. :return: None
  6103. """
  6104. if container:
  6105. plot_container = container
  6106. else:
  6107. plot_container = self.ui.right_layout
  6108. modifier = QtWidgets.QApplication.queryKeyboardModifiers()
  6109. if self.is_legacy is True or modifier == QtCore.Qt.ControlModifier:
  6110. self.is_legacy = True
  6111. self.defaults["global_graphic_engine"] = "2D"
  6112. self.plotcanvas = PlotCanvasLegacy(plot_container, self)
  6113. else:
  6114. try:
  6115. self.plotcanvas = PlotCanvas(plot_container, self)
  6116. except Exception as er:
  6117. msg_txt = traceback.format_exc()
  6118. log.debug("App.on_plotcanvas_setup() failed -> %s" % str(er))
  6119. log.debug("OpenGL canvas initialization failed with the following error.\n" + msg_txt)
  6120. msg = '[ERROR_NOTCL] %s' % _("An internal error has occurred. See shell.\n")
  6121. msg += _("OpenGL canvas initialization failed. HW or HW configuration not supported."
  6122. "Change the graphic engine to Legacy(2D) in Edit -> Preferences -> General tab.\n\n")
  6123. msg += msg_txt
  6124. self.inform.emit(msg)
  6125. return 'fail'
  6126. # So it can receive key presses
  6127. self.plotcanvas.native.setFocus()
  6128. if self.is_legacy is False:
  6129. pan_button = 2 if self.defaults["global_pan_button"] == '2' else 3
  6130. # Set the mouse button for panning
  6131. self.plotcanvas.view.camera.pan_button_setting = pan_button
  6132. self.mm = self.plotcanvas.graph_event_connect('mouse_move', self.on_mouse_move_over_plot)
  6133. self.mp = self.plotcanvas.graph_event_connect('mouse_press', self.on_mouse_click_over_plot)
  6134. self.mr = self.plotcanvas.graph_event_connect('mouse_release', self.on_mouse_click_release_over_plot)
  6135. self.mdc = self.plotcanvas.graph_event_connect('mouse_double_click', self.on_mouse_double_click_over_plot)
  6136. # Keys over plot enabled
  6137. self.kp = self.plotcanvas.graph_event_connect('key_press', self.ui.keyPressEvent)
  6138. if self.defaults['global_cursor_type'] == 'small':
  6139. self.app_cursor = self.plotcanvas.new_cursor()
  6140. else:
  6141. self.app_cursor = self.plotcanvas.new_cursor(big=True)
  6142. if self.ui.grid_snap_btn.isChecked():
  6143. self.app_cursor.enabled = True
  6144. else:
  6145. self.app_cursor.enabled = False
  6146. if self.is_legacy is False:
  6147. self.hover_shapes = ShapeCollection(parent=self.plotcanvas.view.scene, layers=1)
  6148. else:
  6149. # will use the default Matplotlib axes
  6150. self.hover_shapes = ShapeCollectionLegacy(obj=self, app=self, name='hover')
  6151. def on_zoom_fit(self):
  6152. """
  6153. Callback for zoom-fit request. This can be either from the corresponding
  6154. toolbar button or the '1' key when the canvas is focused. Calls ``self.adjust_axes()``
  6155. with axes limits from the geometry bounds of all objects.
  6156. :return: None
  6157. """
  6158. if self.is_legacy is False:
  6159. self.plotcanvas.fit_view()
  6160. else:
  6161. xmin, ymin, xmax, ymax = self.collection.get_bounds()
  6162. width = xmax - xmin
  6163. height = ymax - ymin
  6164. xmin -= 0.05 * width
  6165. xmax += 0.05 * width
  6166. ymin -= 0.05 * height
  6167. ymax += 0.05 * height
  6168. self.plotcanvas.adjust_axes(xmin, ymin, xmax, ymax)
  6169. def on_zoom_in(self):
  6170. """
  6171. Callback for zoom-in request.
  6172. :return:
  6173. """
  6174. self.plotcanvas.zoom(1 / float(self.defaults['global_zoom_ratio']))
  6175. def on_zoom_out(self):
  6176. """
  6177. Callback for zoom-out request.
  6178. :return:
  6179. """
  6180. self.plotcanvas.zoom(float(self.defaults['global_zoom_ratio']))
  6181. def disable_all_plots(self):
  6182. self.defaults.report_usage("disable_all_plots()")
  6183. self.disable_plots(self.collection.get_list())
  6184. self.inform.emit('[success] %s' %
  6185. _("All plots disabled."))
  6186. def disable_other_plots(self):
  6187. self.defaults.report_usage("disable_other_plots()")
  6188. self.disable_plots(self.collection.get_non_selected())
  6189. self.inform.emit('[success] %s' %
  6190. _("All non selected plots disabled."))
  6191. def enable_all_plots(self):
  6192. self.defaults.report_usage("enable_all_plots()")
  6193. self.enable_plots(self.collection.get_list())
  6194. self.inform.emit('[success] %s' %
  6195. _("All plots enabled."))
  6196. def on_enable_sel_plots(self):
  6197. log.debug("App.on_enable_sel_plot()")
  6198. object_list = self.collection.get_selected()
  6199. self.enable_plots(objects=object_list)
  6200. self.inform.emit('[success] %s' % _("Selected plots enabled..."))
  6201. def on_disable_sel_plots(self):
  6202. log.debug("App.on_disable_sel_plot()")
  6203. # self.inform.emit(_("Disabling plots ..."))
  6204. object_list = self.collection.get_selected()
  6205. self.disable_plots(objects=object_list)
  6206. self.inform.emit('[success] %s' % _("Selected plots disabled..."))
  6207. def enable_plots(self, objects):
  6208. """
  6209. Enable plots
  6210. :param objects: list of Objects to be enabled
  6211. :return:
  6212. """
  6213. log.debug("Enabling plots ...")
  6214. # self.inform.emit(_("Working ..."))
  6215. for obj in objects:
  6216. if obj.options['plot'] is False:
  6217. obj.options.set_change_callback(lambda x: None)
  6218. obj.options['plot'] = True
  6219. try:
  6220. # only the Gerber obj has on_plot_cb_click() method
  6221. obj.ui.plot_cb.stateChanged.disconnect(obj.on_plot_cb_click)
  6222. # disable this cb while disconnected,
  6223. # in case the operation takes time the user is not allowed to change it
  6224. obj.ui.plot_cb.setDisabled(True)
  6225. except AttributeError:
  6226. pass
  6227. obj.set_form_item("plot")
  6228. try:
  6229. obj.ui.plot_cb.stateChanged.connect(obj.on_plot_cb_click)
  6230. obj.ui.plot_cb.setDisabled(False)
  6231. except AttributeError:
  6232. pass
  6233. obj.options.set_change_callback(obj.on_options_change)
  6234. def worker_task(objs):
  6235. with self.proc_container.new(_("Enabling plots ...")):
  6236. for plot_obj in objs:
  6237. # obj.options['plot'] = True
  6238. if isinstance(plot_obj, CNCJobObject):
  6239. plot_obj.plot(visible=True, kind=self.defaults["cncjob_plot_kind"])
  6240. else:
  6241. plot_obj.plot(visible=True)
  6242. self.worker_task.emit({'fcn': worker_task, 'params': [objects]})
  6243. def disable_plots(self, objects):
  6244. """
  6245. Disables plots
  6246. :param objects: list of Objects to be disabled
  6247. :return:
  6248. """
  6249. # if no objects selected then do nothing
  6250. if not self.collection.get_selected():
  6251. return
  6252. log.debug("Disabling plots ...")
  6253. # self.inform.emit(_("Working ..."))
  6254. for obj in objects:
  6255. if obj.options['plot'] is True:
  6256. obj.options.set_change_callback(lambda x: None)
  6257. obj.options['plot'] = False
  6258. try:
  6259. # only the Gerber obj has on_plot_cb_click() method
  6260. obj.ui.plot_cb.stateChanged.disconnect(obj.on_plot_cb_click)
  6261. obj.ui.plot_cb.setDisabled(True)
  6262. except AttributeError:
  6263. pass
  6264. obj.set_form_item("plot")
  6265. try:
  6266. obj.ui.plot_cb.stateChanged.connect(obj.on_plot_cb_click)
  6267. obj.ui.plot_cb.setDisabled(False)
  6268. except AttributeError:
  6269. pass
  6270. obj.options.set_change_callback(obj.on_options_change)
  6271. try:
  6272. self.delete_selection_shape()
  6273. except Exception as e:
  6274. log.debug("App.disable_plots() --> %s" % str(e))
  6275. def worker_task(objs):
  6276. with self.proc_container.new(_("Disabling plots ...")):
  6277. for plot_obj in objs:
  6278. # obj.options['plot'] = True
  6279. if isinstance(plot_obj, CNCJobObject):
  6280. plot_obj.plot(visible=False, kind=self.defaults["cncjob_plot_kind"])
  6281. else:
  6282. plot_obj.plot(visible=False)
  6283. self.worker_task.emit({'fcn': worker_task, 'params': [objects]})
  6284. def toggle_plots(self, objects):
  6285. """
  6286. Toggle plots visibility
  6287. :param objects: list of Objects for which to be toggled the visibility
  6288. :return: None
  6289. """
  6290. # if no objects selected then do nothing
  6291. if not self.collection.get_selected():
  6292. return
  6293. log.debug("Toggling plots ...")
  6294. self.inform.emit(_("Working ..."))
  6295. for obj in objects:
  6296. if obj.options['plot'] is False:
  6297. obj.options['plot'] = True
  6298. else:
  6299. obj.options['plot'] = False
  6300. self.app_obj.plots_updated.emit()
  6301. def clear_plots(self):
  6302. """
  6303. Clear the plots
  6304. :return: None
  6305. """
  6306. objects = self.collection.get_list()
  6307. for obj in objects:
  6308. obj.clear(obj == objects[-1])
  6309. # Clear pool to free memory
  6310. self.clear_pool()
  6311. def on_set_color_action_triggered(self):
  6312. """
  6313. This slot gets called by clicking on the menu entry in the Set Color submenu of the context menu in Project Tab
  6314. :return:
  6315. """
  6316. new_color = self.defaults['gerber_plot_fill']
  6317. clicked_action = self.sender()
  6318. assert isinstance(clicked_action, QAction), "Expected a QAction, got %s" % type(clicked_action)
  6319. act_name = clicked_action.text()
  6320. sel_obj_list = self.collection.get_selected()
  6321. if not sel_obj_list:
  6322. return
  6323. # a default value, I just chose this one
  6324. alpha_level = 'BF'
  6325. for sel_obj in sel_obj_list:
  6326. if sel_obj.kind == 'excellon':
  6327. alpha_level = str(hex(
  6328. self.ui.excellon_defaults_form.excellon_gen_group.excellon_alpha_entry.get_value())[2:])
  6329. elif sel_obj.kind == 'gerber':
  6330. alpha_level = str(hex(self.ui.gerber_defaults_form.gerber_gen_group.gerber_alpha_entry.get_value())[2:])
  6331. elif sel_obj.kind == 'geometry':
  6332. alpha_level = 'FF'
  6333. else:
  6334. log.debug(
  6335. "App.on_set_color_action_triggered() --> Default alpfa for this object type not supported yet")
  6336. continue
  6337. sel_obj.alpha_level = alpha_level
  6338. if act_name == _('Red'):
  6339. new_color = '#FF0000' + alpha_level
  6340. if act_name == _('Blue'):
  6341. new_color = '#0000FF' + alpha_level
  6342. if act_name == _('Yellow'):
  6343. new_color = '#FFDF00' + alpha_level
  6344. if act_name == _('Green'):
  6345. new_color = '#00FF00' + alpha_level
  6346. if act_name == _('Purple'):
  6347. new_color = '#FF00FF' + alpha_level
  6348. if act_name == _('Brown'):
  6349. new_color = '#A52A2A' + alpha_level
  6350. if act_name == _('White'):
  6351. new_color = '#FFFFFF' + alpha_level
  6352. if act_name == _('Black'):
  6353. new_color = '#000000' + alpha_level
  6354. if act_name == _('Custom'):
  6355. new_color = QtGui.QColor(self.defaults['gerber_plot_fill'][:7])
  6356. c_dialog = QtWidgets.QColorDialog()
  6357. plot_fill_color = c_dialog.getColor(initial=new_color)
  6358. if plot_fill_color.isValid() is False:
  6359. return
  6360. new_color = str(plot_fill_color.name()) + alpha_level
  6361. if act_name == _("Default"):
  6362. for sel_obj in sel_obj_list:
  6363. if sel_obj.kind == 'excellon':
  6364. new_color = self.defaults['excellon_plot_fill']
  6365. new_line_color = self.defaults['excellon_plot_line']
  6366. elif sel_obj.kind == 'gerber':
  6367. new_color = self.defaults['gerber_plot_fill']
  6368. new_line_color = self.defaults['gerber_plot_line']
  6369. elif sel_obj.kind == 'geometry':
  6370. new_color = self.defaults['geometry_plot_line']
  6371. new_line_color = self.defaults['geometry_plot_line']
  6372. else:
  6373. log.debug(
  6374. "App.on_set_color_action_triggered() --> Default color for this object type not supported yet")
  6375. continue
  6376. sel_obj.fill_color = new_color
  6377. sel_obj.outline_color = new_line_color
  6378. sel_obj.shapes.redraw(
  6379. update_colors=(new_color, new_line_color)
  6380. )
  6381. return
  6382. if act_name == _("Opacity"):
  6383. # alpha_level, ok_button = QtWidgets.QInputDialog.getInt(
  6384. # self.ui, _("Set alpha level ..."), '%s:' % _("Value"), min=0, max=255, step=1, value=191)
  6385. alpha_dialog = FCInputDialogSlider(
  6386. self.ui, _("Set alpha level ..."), '%s:' % _("Value"), min=0, max=255, step=1, init_val=191)
  6387. alpha_level, ok_button = alpha_dialog.get_results()
  6388. if ok_button:
  6389. alpha_str = str(hex(alpha_level)[2:]) if alpha_level != 0 else '00'
  6390. for sel_obj in sel_obj_list:
  6391. sel_obj.fill_color = sel_obj.fill_color[:-2] + alpha_str
  6392. sel_obj.shapes.redraw(
  6393. update_colors=(sel_obj.fill_color, sel_obj.outline_color)
  6394. )
  6395. return
  6396. new_line_color = color_variant(new_color[:7], 0.7)
  6397. if act_name == _("White"):
  6398. new_line_color = color_variant("#dedede", 0.7)
  6399. for sel_obj in sel_obj_list:
  6400. sel_obj.fill_color = new_color
  6401. sel_obj.outline_color = new_line_color
  6402. sel_obj.shapes.redraw(
  6403. update_colors=(new_color, new_line_color)
  6404. )
  6405. # make sure to set the color in the Gerber colors storage self.defaults["gerber_color_list"]
  6406. group = self.collection.group_items["gerber"]
  6407. group_index = self.collection.index(group.row(), 0, QtCore.QModelIndex())
  6408. new_c = (new_line_color, new_color)
  6409. for sel_obj in sel_obj_list:
  6410. if sel_obj.kind == 'gerber':
  6411. item = sel_obj.item
  6412. item_index = self.collection.index(item.row(), 0, group_index)
  6413. idx = item_index.row()
  6414. self.defaults["gerber_color_list"][idx] = new_c
  6415. def generate_cnc_job(self, objects):
  6416. """
  6417. Slot that will be called by clicking an entry in the contextual menu generated in the Project Tab tree
  6418. :param objects: Selected objects in the Project Tab
  6419. :return:
  6420. """
  6421. self.defaults.report_usage("generate_cnc_job()")
  6422. # for obj in objects:
  6423. # obj.generatecncjob()
  6424. for obj in objects:
  6425. obj.on_generatecnc_button_click()
  6426. def start_delayed_quit(self, delay, filename, should_quit=None):
  6427. """
  6428. :param delay: period of checking if project file size is more than zero; in seconds
  6429. :param filename: the name of the project file to be checked periodically for size more than zero
  6430. :param should_quit: if the task finished will be followed by an app quit; boolean
  6431. :return:
  6432. """
  6433. to_quit = should_quit
  6434. self.save_timer = QtCore.QTimer()
  6435. self.save_timer.setInterval(delay)
  6436. self.save_timer.timeout.connect(lambda: self.check_project_file_size(filename=filename, should_quit=to_quit))
  6437. self.save_timer.start()
  6438. def check_project_file_size(self, filename, should_quit=None):
  6439. """
  6440. :param filename: the name of the project file to be checked periodically for size more than zero
  6441. :param should_quit: will quit the app if True; boolean
  6442. :return:
  6443. """
  6444. try:
  6445. if os.stat(filename).st_size > 0:
  6446. self.save_in_progress = False
  6447. self.save_timer.stop()
  6448. if should_quit:
  6449. self.app_quit.emit()
  6450. except Exception:
  6451. traceback.print_exc()
  6452. def save_project_auto(self):
  6453. """
  6454. Called periodically to save the project.
  6455. It will save if there is no block on the save, if the project was saved at least once and if there is no save in
  6456. # progress.
  6457. :return:
  6458. """
  6459. if self.block_autosave is False and self.should_we_save is True and self.save_in_progress is False:
  6460. self.on_file_saveproject()
  6461. def save_project_auto_update(self):
  6462. """
  6463. Update the auto save time interval value.
  6464. :return:
  6465. """
  6466. log.debug("App.save_project_auto_update() --> updated the interval timeout.")
  6467. try:
  6468. if self.autosave_timer.isActive():
  6469. self.autosave_timer.stop()
  6470. except Exception:
  6471. pass
  6472. if self.defaults['global_autosave'] is True:
  6473. self.autosave_timer.setInterval(int(self.defaults['global_autosave_timeout']))
  6474. self.autosave_timer.start()
  6475. def on_options_app2project(self):
  6476. """
  6477. Callback for Options->Transfer Options->App=>Project. Copies options
  6478. from application defaults to project defaults.
  6479. :return: None
  6480. """
  6481. self.defaults.report_usage("on_options_app2project")
  6482. self.preferencesUiManager.defaults_read_form()
  6483. self.options.update(self.defaults)
  6484. def shell_message(self, msg, show=False, error=False, warning=False, success=False, selected=False, new_line=True):
  6485. """
  6486. Shows a message on the FlatCAM Shell
  6487. :param msg: Message to display.
  6488. :param show: Opens the shell.
  6489. :param error: Shows the message as an error.
  6490. :param warning: Shows the message as an warning.
  6491. :param success: Shows the message as an success.
  6492. :param selected: Indicate that something was selected on canvas
  6493. :return: None
  6494. """
  6495. end = '\n' if new_line is True else ''
  6496. if show:
  6497. self.ui.shell_dock.show()
  6498. try:
  6499. if error:
  6500. self.shell.append_error(msg + end)
  6501. elif warning:
  6502. self.shell.append_warning(msg + end)
  6503. elif success:
  6504. self.shell.append_success(msg + end)
  6505. elif selected:
  6506. self.shell.append_selected(msg + end)
  6507. else:
  6508. self.shell.append_output(msg + end)
  6509. except AttributeError:
  6510. log.debug("shell_message() is called before Shell Class is instantiated. The message is: %s", str(msg))
  6511. def dec_format(self, val, dec=None):
  6512. """
  6513. Returns a formatted float value with a certain number of decimals
  6514. """
  6515. dec_nr = dec if dec is not None else self.decimals
  6516. return float('%.*f' % (dec_nr, val))
  6517. class ArgsThread(QtCore.QObject):
  6518. open_signal = pyqtSignal(list)
  6519. start = pyqtSignal()
  6520. stop = pyqtSignal()
  6521. if sys.platform == 'win32':
  6522. address = (r'\\.\pipe\NPtest', 'AF_PIPE')
  6523. else:
  6524. address = ('/tmp/testipc', 'AF_UNIX')
  6525. def __init__(self):
  6526. super().__init__()
  6527. self.listener = None
  6528. self.thread_exit = False
  6529. self.start.connect(self.run)
  6530. self.stop.connect(self.close_listener)
  6531. def my_loop(self, address):
  6532. try:
  6533. self.listener = Listener(*address)
  6534. while self.thread_exit is False:
  6535. conn = self.listener.accept()
  6536. self.serve(conn)
  6537. except socket.error:
  6538. try:
  6539. conn = Client(*address)
  6540. conn.send(sys.argv)
  6541. conn.send('close')
  6542. # close the current instance only if there are args
  6543. if len(sys.argv) > 1:
  6544. try:
  6545. self.listener.close()
  6546. except Exception:
  6547. pass
  6548. sys.exit()
  6549. except ConnectionRefusedError:
  6550. if sys.platform == 'win32':
  6551. pass
  6552. else:
  6553. os.system('rm /tmp/testipc')
  6554. self.listener = Listener(*address)
  6555. while True:
  6556. conn = self.listener.accept()
  6557. self.serve(conn)
  6558. def serve(self, conn):
  6559. while self.thread_exit is False:
  6560. msg = conn.recv()
  6561. if msg == 'close':
  6562. break
  6563. self.open_signal.emit(msg)
  6564. conn.close()
  6565. # the decorator is a must; without it this technique will not work unless the start signal is connected
  6566. # in the main thread (where this class is instantiated) after the instance is moved o the new thread
  6567. @pyqtSlot()
  6568. def run(self):
  6569. self.my_loop(self.address)
  6570. @pyqtSlot()
  6571. def close_listener(self):
  6572. self.thread_exit = True
  6573. self.listener.close()
  6574. class MenuFileHandlers(QtCore.QObject):
  6575. def __init__(self, app):
  6576. super().__init__()
  6577. self.app = app
  6578. self.inform = self.app.inform
  6579. self.splash = self.app.splash
  6580. self.worker_task = self.app.worker_task
  6581. self.defaults = self.app.defaults
  6582. self.pagesize = {}
  6583. def on_fileopengerber(self, signal, name=None):
  6584. """
  6585. File menu callback for opening a Gerber.
  6586. :param signal: required because clicking the entry will generate a checked signal which needs a container
  6587. :param name:
  6588. :return: None
  6589. """
  6590. self.app.log.debug("on_fileopengerber()")
  6591. _filter_ = "Gerber Files (*.gbr *.ger *.gtl *.gbl *.gts *.gbs *.gtp *.gbp *.gto *.gbo *.gm1 *.gml *.gm3 " \
  6592. "*.gko *.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim *.mil *.grb " \
  6593. "*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb *.pho *.gdo *.art *.gbd *.outline);;" \
  6594. "Protel Files (*.gtl *.gbl *.gts *.gbs *.gto *.gbo *.gtp *.gbp *.gml *.gm1 *.gm3 *.gko " \
  6595. "*.outline);;" \
  6596. "Eagle Files (*.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim " \
  6597. "*.mil);;" \
  6598. "OrCAD Files (*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb);;" \
  6599. "Allegro Files (*.art);;" \
  6600. "Mentor Files (*.pho *.gdo);;" \
  6601. "All Files (*.*)"
  6602. if name is None:
  6603. try:
  6604. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Gerber"),
  6605. directory=self.app.get_last_folder(),
  6606. filter=_filter_,
  6607. initialFilter=self.app.last_op_gerber_filter)
  6608. except TypeError:
  6609. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Gerber"), filter=_filter_)
  6610. filenames = [str(filename) for filename in filenames]
  6611. self.app.last_op_gerber_filter = _f
  6612. else:
  6613. filenames = [name]
  6614. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  6615. "Canvas initialization finished in"),
  6616. '%.2f' % self.app.used_time,
  6617. _("Opening Gerber file.")),
  6618. alignment=Qt.AlignBottom | Qt.AlignLeft,
  6619. color=QtGui.QColor("gray"))
  6620. if len(filenames) == 0:
  6621. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6622. else:
  6623. for filename in filenames:
  6624. if filename != '':
  6625. self.worker_task.emit({'fcn': self.open_gerber, 'params': [filename]})
  6626. def on_fileopenexcellon(self, signal, name=None):
  6627. """
  6628. File menu callback for opening an Excellon file.
  6629. :param signal: required because clicking the entry will generate a checked signal which needs a container
  6630. :param name:
  6631. :return: None
  6632. """
  6633. self.app.log.debug("on_fileopenexcellon()")
  6634. _filter_ = "Excellon Files (*.drl *.txt *.xln *.drd *.tap *.exc *.ncd);;" \
  6635. "All Files (*.*)"
  6636. if name is None:
  6637. try:
  6638. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Excellon"),
  6639. directory=self.app.get_last_folder(),
  6640. filter=_filter_,
  6641. initialFilter=self.app.last_op_excellon_filter)
  6642. except TypeError:
  6643. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Excellon"), filter=_filter_)
  6644. filenames = [str(filename) for filename in filenames]
  6645. self.app.last_op_excellon_filter = _f
  6646. else:
  6647. filenames = [str(name)]
  6648. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  6649. "Canvas initialization finished in"),
  6650. '%.2f' % self.app.used_time,
  6651. _("Opening Excellon file.")),
  6652. alignment=Qt.AlignBottom | Qt.AlignLeft,
  6653. color=QtGui.QColor("gray"))
  6654. if len(filenames) == 0:
  6655. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6656. else:
  6657. for filename in filenames:
  6658. if filename != '':
  6659. self.worker_task.emit({'fcn': self.open_excellon, 'params': [filename]})
  6660. def on_fileopengcode(self, signal, name=None):
  6661. """
  6662. File menu call back for opening gcode.
  6663. :param signal: required because clicking the entry will generate a checked signal which needs a container
  6664. :param name:
  6665. :return:
  6666. """
  6667. self.app.log.debug("on_fileopengcode()")
  6668. # https://bobcadsupport.com/helpdesk/index.php?/Knowledgebase/Article/View/13/5/known-g-code-file-extensions
  6669. _filter_ = "G-Code Files (*.txt *.nc *.ncc *.tap *.gcode *.cnc *.ecs *.fnc *.dnc *.ncg *.gc *.fan *.fgc" \
  6670. " *.din *.xpi *.hnc *.h *.i *.ncp *.min *.gcd *.rol *.mpr *.ply *.out *.eia *.sbp *.mpf);;" \
  6671. "All Files (*.*)"
  6672. if name is None:
  6673. try:
  6674. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open G-Code"),
  6675. directory=self.app.get_last_folder(),
  6676. filter=_filter_,
  6677. initialFilter=self.app.last_op_gcode_filter)
  6678. except TypeError:
  6679. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open G-Code"), filter=_filter_)
  6680. filenames = [str(filename) for filename in filenames]
  6681. self.app.last_op_gcode_filter = _f
  6682. else:
  6683. filenames = [name]
  6684. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  6685. "Canvas initialization finished in"),
  6686. '%.2f' % self.app.used_time,
  6687. _("Opening G-Code file.")),
  6688. alignment=Qt.AlignBottom | Qt.AlignLeft,
  6689. color=QtGui.QColor("gray"))
  6690. if len(filenames) == 0:
  6691. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6692. else:
  6693. for filename in filenames:
  6694. if filename != '':
  6695. self.worker_task.emit({'fcn': self.open_gcode, 'params': [filename, None, True]})
  6696. def on_file_openproject(self, signal):
  6697. """
  6698. File menu callback for opening a project.
  6699. :param signal: required because clicking the entry will generate a checked signal which needs a container
  6700. :return: None
  6701. """
  6702. self.app.log.debug("on_file_openproject()")
  6703. _filter_ = "FlatCAM Project (*.FlatPrj);;All Files (*.*)"
  6704. try:
  6705. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Project"),
  6706. directory=self.app.get_last_folder(), filter=_filter_)
  6707. except TypeError:
  6708. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Project"), filter=_filter_)
  6709. filename = str(filename)
  6710. if filename == "":
  6711. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6712. else:
  6713. # self.worker_task.emit({'fcn': self.open_project,
  6714. # 'params': [filename]})
  6715. # The above was failing because open_project() is not
  6716. # thread safe. The new_project()
  6717. self.open_project(filename)
  6718. def on_fileopenhpgl2(self, signal, name=None):
  6719. """
  6720. File menu callback for opening a HPGL2.
  6721. :param signal: required because clicking the entry will generate a checked signal which needs a container
  6722. :param name:
  6723. :return: None
  6724. """
  6725. self.app.log.debug("on_fileopenhpgl2()")
  6726. _filter_ = "HPGL2 Files (*.plt);;" \
  6727. "All Files (*.*)"
  6728. if name is None:
  6729. try:
  6730. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open HPGL2"),
  6731. directory=self.app.get_last_folder(),
  6732. filter=_filter_)
  6733. except TypeError:
  6734. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open HPGL2"), filter=_filter_)
  6735. filenames = [str(filename) for filename in filenames]
  6736. else:
  6737. filenames = [name]
  6738. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  6739. "Canvas initialization finished in"),
  6740. '%.2f' % self.app.used_time,
  6741. _("Opening HPGL2 file.")),
  6742. alignment=Qt.AlignBottom | Qt.AlignLeft,
  6743. color=QtGui.QColor("gray"))
  6744. if len(filenames) == 0:
  6745. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6746. else:
  6747. for filename in filenames:
  6748. if filename != '':
  6749. self.worker_task.emit({'fcn': self.open_hpgl2, 'params': [filename]})
  6750. def on_file_openconfig(self, signal):
  6751. """
  6752. File menu callback for opening a config file.
  6753. :param signal: required because clicking the entry will generate a checked signal which needs a container
  6754. :return: None
  6755. """
  6756. self.app.log.debug("on_file_openconfig()")
  6757. _filter_ = "FlatCAM Config (*.FlatConfig);;FlatCAM Config (*.json);;All Files (*.*)"
  6758. try:
  6759. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Configuration File"),
  6760. directory=self.app.data_path, filter=_filter_)
  6761. except TypeError:
  6762. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Configuration File"),
  6763. filter=_filter_)
  6764. if filename == "":
  6765. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6766. else:
  6767. self.open_config_file(filename)
  6768. def on_file_exportsvg(self):
  6769. """
  6770. Callback for menu item File->Export SVG.
  6771. :return: None
  6772. """
  6773. self.app.log.debug("on_file_exportsvg()")
  6774. obj = self.app.collection.get_active()
  6775. if obj is None:
  6776. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6777. msg = _("Please Select a Geometry object to export")
  6778. msgbox = QtWidgets.QMessageBox()
  6779. msgbox.setIcon(QtWidgets.QMessageBox.Warning)
  6780. msgbox.setInformativeText(msg)
  6781. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  6782. msgbox.setDefaultButton(bt_ok)
  6783. msgbox.exec_()
  6784. return
  6785. # Check for more compatible types and add as required
  6786. if (not isinstance(obj, GeometryObject)
  6787. and not isinstance(obj, GerberObject)
  6788. and not isinstance(obj, CNCJobObject)
  6789. and not isinstance(obj, ExcellonObject)):
  6790. msg = '[ERROR_NOTCL] %s' % _("Only Geometry, Gerber and CNCJob objects can be used.")
  6791. msgbox = QtWidgets.QMessageBox()
  6792. msgbox.setIcon(QtWidgets.QMessageBox.Warning)
  6793. msgbox.setInformativeText(msg)
  6794. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  6795. msgbox.setDefaultButton(bt_ok)
  6796. msgbox.exec_()
  6797. return
  6798. name = obj.options["name"]
  6799. _filter = "SVG File (*.svg);;All Files (*.*)"
  6800. try:
  6801. filename, _f = FCFileSaveDialog.get_saved_filename(
  6802. caption=_("Export SVG"),
  6803. directory=self.app.get_last_save_folder() + '/' + str(name) + '_svg',
  6804. ext_filter=_filter)
  6805. except TypeError:
  6806. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export SVG"), ext_filter=_filter)
  6807. filename = str(filename)
  6808. if filename == "":
  6809. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6810. return
  6811. else:
  6812. self.export_svg(name, filename)
  6813. if self.defaults["global_open_style"] is False:
  6814. self.app.file_opened.emit("SVG", filename)
  6815. self.app.file_saved.emit("SVG", filename)
  6816. def on_file_exportpng(self):
  6817. self.app.log.debug("on_file_exportpng()")
  6818. date = str(datetime.today()).rpartition('.')[0]
  6819. date = ''.join(c for c in date if c not in ':-')
  6820. date = self.app.date.replace(' ', '_')
  6821. data = None
  6822. if self.app.is_legacy is False:
  6823. image = _screenshot(alpha=False)
  6824. data = np.asarray(image)
  6825. if not data.ndim == 3 and data.shape[-1] in (3, 4):
  6826. self.inform.emit('[[WARNING_NOTCL]] %s' % _('Data must be a 3D array with last dimension 3 or 4'))
  6827. return
  6828. filter_ = "PNG File (*.png);;All Files (*.*)"
  6829. try:
  6830. filename, _f = FCFileSaveDialog.get_saved_filename(
  6831. caption=_("Export PNG Image"),
  6832. directory=self.app.get_last_save_folder() + '/png_' + date,
  6833. ext_filter=filter_)
  6834. except TypeError:
  6835. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export PNG Image"), ext_filter=filter_)
  6836. filename = str(filename)
  6837. if filename == "":
  6838. self.inform.emit(_("Cancelled."))
  6839. return
  6840. else:
  6841. if self.app.is_legacy is False:
  6842. write_png(filename, data)
  6843. else:
  6844. self.app.plotcanvas.figure.savefig(filename)
  6845. if self.defaults["global_open_style"] is False:
  6846. self.app.file_opened.emit("png", filename)
  6847. self.app.file_saved.emit("png", filename)
  6848. def on_file_savegerber(self):
  6849. """
  6850. Callback for menu item in Project context menu.
  6851. :return: None
  6852. """
  6853. self.app.log.debug("on_file_savegerber()")
  6854. obj = self.app.collection.get_active()
  6855. if obj is None:
  6856. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6857. return
  6858. # Check for more compatible types and add as required
  6859. if not isinstance(obj, GerberObject):
  6860. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Gerber objects can be saved as Gerber files..."))
  6861. return
  6862. name = self.app.collection.get_active().options["name"]
  6863. _filter = "Gerber File (*.GBR);;Gerber File (*.GRB);;All Files (*.*)"
  6864. try:
  6865. filename, _f = FCFileSaveDialog.get_saved_filename(
  6866. caption="Save Gerber source file",
  6867. directory=self.app.get_last_save_folder() + '/' + name,
  6868. ext_filter=_filter)
  6869. except TypeError:
  6870. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Gerber source file"), ext_filter=_filter)
  6871. filename = str(filename)
  6872. if filename == "":
  6873. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6874. return
  6875. else:
  6876. self.save_source_file(name, filename)
  6877. if self.defaults["global_open_style"] is False:
  6878. self.app.file_opened.emit("Gerber", filename)
  6879. self.app.file_saved.emit("Gerber", filename)
  6880. def on_file_savescript(self):
  6881. """
  6882. Callback for menu item in Project context menu.
  6883. :return: None
  6884. """
  6885. self.app.log.debug("on_file_savescript()")
  6886. obj = self.app.collection.get_active()
  6887. if obj is None:
  6888. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6889. return
  6890. # Check for more compatible types and add as required
  6891. if not isinstance(obj, ScriptObject):
  6892. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Script objects can be saved as TCL Script files..."))
  6893. return
  6894. name = self.app.collection.get_active().options["name"]
  6895. _filter = "FlatCAM Scripts (*.FlatScript);;All Files (*.*)"
  6896. try:
  6897. filename, _f = FCFileSaveDialog.get_saved_filename(
  6898. caption="Save Script source file",
  6899. directory=self.app.get_last_save_folder() + '/' + name,
  6900. ext_filter=_filter)
  6901. except TypeError:
  6902. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Script source file"), ext_filter=_filter)
  6903. filename = str(filename)
  6904. if filename == "":
  6905. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6906. return
  6907. else:
  6908. self.save_source_file(name, filename)
  6909. if self.defaults["global_open_style"] is False:
  6910. self.app.file_opened.emit("Script", filename)
  6911. self.app.file_saved.emit("Script", filename)
  6912. def on_file_savedocument(self):
  6913. """
  6914. Callback for menu item in Project context menu.
  6915. :return: None
  6916. """
  6917. self.app.log.debug("on_file_savedocument()")
  6918. obj = self.app.collection.get_active()
  6919. if obj is None:
  6920. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6921. return
  6922. # Check for more compatible types and add as required
  6923. if not isinstance(obj, ScriptObject):
  6924. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Document objects can be saved as Document files..."))
  6925. return
  6926. name = self.app.collection.get_active().options["name"]
  6927. _filter = "FlatCAM Documents (*.FlatDoc);;All Files (*.*)"
  6928. try:
  6929. filename, _f = FCFileSaveDialog.get_saved_filename(
  6930. caption="Save Document source file",
  6931. directory=self.app.get_last_save_folder() + '/' + name,
  6932. ext_filter=_filter)
  6933. except TypeError:
  6934. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Document source file"),
  6935. ext_filter=_filter)
  6936. filename = str(filename)
  6937. if filename == "":
  6938. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6939. return
  6940. else:
  6941. self.save_source_file(name, filename)
  6942. if self.defaults["global_open_style"] is False:
  6943. self.app.file_opened.emit("Document", filename)
  6944. self.app.file_saved.emit("Document", filename)
  6945. def on_file_saveexcellon(self):
  6946. """
  6947. Callback for menu item in project context menu.
  6948. :return: None
  6949. """
  6950. self.app.log.debug("on_file_saveexcellon()")
  6951. obj = self.app.collection.get_active()
  6952. if obj is None:
  6953. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6954. return
  6955. # Check for more compatible types and add as required
  6956. if not isinstance(obj, ExcellonObject):
  6957. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Excellon objects can be saved as Excellon files..."))
  6958. return
  6959. name = self.app.collection.get_active().options["name"]
  6960. _filter = "Excellon File (*.DRL);;Excellon File (*.TXT);;All Files (*.*)"
  6961. try:
  6962. filename, _f = FCFileSaveDialog.get_saved_filename(
  6963. caption=_("Save Excellon source file"),
  6964. directory=self.app.get_last_save_folder() + '/' + name,
  6965. ext_filter=_filter)
  6966. except TypeError:
  6967. filename, _f = FCFileSaveDialog.get_saved_filename(
  6968. caption=_("Save Excellon source file"), ext_filter=_filter)
  6969. filename = str(filename)
  6970. if filename == "":
  6971. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6972. return
  6973. else:
  6974. self.save_source_file(name, filename)
  6975. if self.defaults["global_open_style"] is False:
  6976. self.app.file_opened.emit("Excellon", filename)
  6977. self.app.file_saved.emit("Excellon", filename)
  6978. def on_file_exportexcellon(self):
  6979. """
  6980. Callback for menu item File->Export->Excellon.
  6981. :return: None
  6982. """
  6983. self.app.log.debug("on_file_exportexcellon()")
  6984. obj = self.app.collection.get_active()
  6985. if obj is None:
  6986. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6987. return
  6988. # Check for more compatible types and add as required
  6989. if not isinstance(obj, ExcellonObject):
  6990. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Excellon objects can be saved as Excellon files..."))
  6991. return
  6992. name = self.app.collection.get_active().options["name"]
  6993. _filter = self.defaults["excellon_save_filters"]
  6994. try:
  6995. filename, _f = FCFileSaveDialog.get_saved_filename(
  6996. caption=_("Export Excellon"),
  6997. directory=self.app.get_last_save_folder() + '/' + name,
  6998. ext_filter=_filter)
  6999. except TypeError:
  7000. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export Excellon"), ext_filter=_filter)
  7001. filename = str(filename)
  7002. if filename == "":
  7003. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  7004. return
  7005. else:
  7006. used_extension = filename.rpartition('.')[2]
  7007. obj.update_filters(last_ext=used_extension, filter_string='excellon_save_filters')
  7008. self.export_excellon(name, filename)
  7009. if self.defaults["global_open_style"] is False:
  7010. self.app.file_opened.emit("Excellon", filename)
  7011. self.app.file_saved.emit("Excellon", filename)
  7012. def on_file_exportgerber(self):
  7013. """
  7014. Callback for menu item File->Export->Gerber.
  7015. :return: None
  7016. """
  7017. App.log.debug("on_file_exportgerber()")
  7018. obj = self.app.collection.get_active()
  7019. if obj is None:
  7020. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  7021. return
  7022. # Check for more compatible types and add as required
  7023. if not isinstance(obj, GerberObject):
  7024. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Gerber objects can be saved as Gerber files..."))
  7025. return
  7026. name = self.app.collection.get_active().options["name"]
  7027. _filter_ = self.defaults['gerber_save_filters']
  7028. try:
  7029. filename, _f = FCFileSaveDialog.get_saved_filename(
  7030. caption=_("Export Gerber"),
  7031. directory=self.app.get_last_save_folder() + '/' + name,
  7032. ext_filter=_filter_)
  7033. except TypeError:
  7034. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export Gerber"), ext_filter=_filter_)
  7035. filename = str(filename)
  7036. if filename == "":
  7037. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  7038. return
  7039. else:
  7040. used_extension = filename.rpartition('.')[2]
  7041. obj.update_filters(last_ext=used_extension, filter_string='gerber_save_filters')
  7042. self.export_gerber(name, filename)
  7043. if self.defaults["global_open_style"] is False:
  7044. self.app.file_opened.emit("Gerber", filename)
  7045. self.app.file_saved.emit("Gerber", filename)
  7046. def on_file_exportdxf(self):
  7047. """
  7048. Callback for menu item File->Export DXF.
  7049. :return: None
  7050. """
  7051. App.log.debug("on_file_exportdxf()")
  7052. obj = self.app.collection.get_active()
  7053. if obj is None:
  7054. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  7055. msg = _("Please Select a Geometry object to export")
  7056. msgbox = QtWidgets.QMessageBox()
  7057. msgbox.setIcon(QtWidgets.QMessageBox.Warning)
  7058. msgbox.setInformativeText(msg)
  7059. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  7060. msgbox.setDefaultButton(bt_ok)
  7061. msgbox.exec_()
  7062. return
  7063. # Check for more compatible types and add as required
  7064. if not isinstance(obj, GeometryObject):
  7065. msg = '[ERROR_NOTCL] %s' % _("Only Geometry objects can be used.")
  7066. msgbox = QtWidgets.QMessageBox()
  7067. msgbox.setIcon(QtWidgets.QMessageBox.Warning)
  7068. msgbox.setInformativeText(msg)
  7069. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  7070. msgbox.setDefaultButton(bt_ok)
  7071. msgbox.exec_()
  7072. return
  7073. name = self.app.collection.get_active().options["name"]
  7074. _filter_ = "DXF File .dxf (*.DXF);;All Files (*.*)"
  7075. try:
  7076. filename, _f = FCFileSaveDialog.get_saved_filename(
  7077. caption=_("Export DXF"),
  7078. directory=self.app.get_last_save_folder() + '/' + name,
  7079. ext_filter=_filter_)
  7080. except TypeError:
  7081. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export DXF"), ext_filter=_filter_)
  7082. filename = str(filename)
  7083. if filename == "":
  7084. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  7085. return
  7086. else:
  7087. self.export_dxf(name, filename)
  7088. if self.defaults["global_open_style"] is False:
  7089. self.app.file_opened.emit("DXF", filename)
  7090. self.app.file_saved.emit("DXF", filename)
  7091. def on_file_importsvg(self, type_of_obj):
  7092. """
  7093. Callback for menu item File->Import SVG.
  7094. :param type_of_obj: to import the SVG as Geometry or as Gerber
  7095. :type type_of_obj: str
  7096. :return: None
  7097. """
  7098. self.app.log.debug("on_file_importsvg()")
  7099. _filter_ = "SVG File .svg (*.svg);;All Files (*.*)"
  7100. try:
  7101. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import SVG"),
  7102. directory=self.app.get_last_folder(),
  7103. filter=_filter_)
  7104. except TypeError:
  7105. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import SVG"),
  7106. filter=_filter_)
  7107. if type_of_obj != "geometry" and type_of_obj != "gerber":
  7108. type_of_obj = "geometry"
  7109. filenames = [str(filename) for filename in filenames]
  7110. if len(filenames) == 0:
  7111. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  7112. else:
  7113. for filename in filenames:
  7114. if filename != '':
  7115. self.worker_task.emit({'fcn': self.import_svg, 'params': [filename, type_of_obj]})
  7116. def on_file_importdxf(self, type_of_obj):
  7117. """
  7118. Callback for menu item File->Import DXF.
  7119. :param type_of_obj: to import the DXF as Geometry or as Gerber
  7120. :type type_of_obj: str
  7121. :return: None
  7122. """
  7123. self.app.log.debug("on_file_importdxf()")
  7124. _filter_ = "DXF File .dxf (*.DXF);;All Files (*.*)"
  7125. try:
  7126. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import DXF"),
  7127. directory=self.app.get_last_folder(),
  7128. filter=_filter_)
  7129. except TypeError:
  7130. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import DXF"),
  7131. filter=_filter_)
  7132. if type_of_obj != "geometry" and type_of_obj != "gerber":
  7133. type_of_obj = "geometry"
  7134. filenames = [str(filename) for filename in filenames]
  7135. if len(filenames) == 0:
  7136. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  7137. else:
  7138. for filename in filenames:
  7139. if filename != '':
  7140. self.worker_task.emit({'fcn': self.import_dxf, 'params': [filename, type_of_obj]})
  7141. def on_file_new_click(self):
  7142. """
  7143. Callback for menu item File -> New.
  7144. Executed on clicking the Menu -> File -> New Project
  7145. :return:
  7146. """
  7147. if self.app.collection.get_list() and self.app.should_we_save:
  7148. msgbox = QtWidgets.QMessageBox()
  7149. # msgbox.setText("<B>Save changes ...</B>")
  7150. msgbox.setText(_("There are files/objects opened in FlatCAM.\n"
  7151. "Creating a New project will delete them.\n"
  7152. "Do you want to Save the project?"))
  7153. msgbox.setWindowTitle(_("Save changes"))
  7154. msgbox.setWindowIcon(QtGui.QIcon(self.app.resource_location + '/save_as.png'))
  7155. msgbox.setIcon(QtWidgets.QMessageBox.Question)
  7156. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  7157. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  7158. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  7159. msgbox.setDefaultButton(bt_yes)
  7160. msgbox.exec_()
  7161. response = msgbox.clickedButton()
  7162. if response == bt_yes:
  7163. self.on_file_saveprojectas()
  7164. elif response == bt_cancel:
  7165. return
  7166. elif response == bt_no:
  7167. self.on_file_new()
  7168. else:
  7169. self.on_file_new()
  7170. self.inform.emit('[success] %s...' % _("New Project created"))
  7171. def on_file_new(self, cli=None):
  7172. """
  7173. Returns the application to its startup state. This method is thread-safe.
  7174. :param cli: Boolean. If True this method was run from command line
  7175. :return: None
  7176. """
  7177. self.defaults.report_usage("on_file_new")
  7178. # Remove everything from memory
  7179. self.app.log.debug("on_file_new()")
  7180. # close any editor that might be open
  7181. if self.app.call_source != 'app':
  7182. self.app.editor2object(cleanup=True)
  7183. # ## EDITOR section
  7184. self.app.geo_editor = AppGeoEditor(self.app)
  7185. self.app.exc_editor = AppExcEditor(self.app)
  7186. self.app.grb_editor = AppGerberEditor(self.app)
  7187. # Clear pool
  7188. self.app.clear_pool()
  7189. for obj in self.app.collection.get_list():
  7190. # delete shapes left drawn from mark shape_collections, if any
  7191. if isinstance(obj, GerberObject):
  7192. try:
  7193. obj.mark_shapes_storage.clear()
  7194. obj.mark_shapes.clear(update=True)
  7195. obj.mark_shapes.enabled = False
  7196. except AttributeError:
  7197. pass
  7198. # also delete annotation shapes, if any
  7199. elif isinstance(obj, CNCJobObject):
  7200. try:
  7201. obj.text_col.enabled = False
  7202. del obj.text_col
  7203. obj.annotation.clear(update=True)
  7204. del obj.annotation
  7205. except AttributeError:
  7206. pass
  7207. # delete the exclusion areas
  7208. self.app.exc_areas.clear_shapes()
  7209. # tcl needs to be reinitialized, otherwise old shell variables etc remains
  7210. self.app.shell.init_tcl()
  7211. # delete any selection shape on canvas
  7212. self.app.delete_selection_shape()
  7213. # delete all FlatCAM objects
  7214. self.app.collection.delete_all()
  7215. # add in Selected tab an initial text that describe the flow of work in FlatCAm
  7216. self.app.setup_default_properties_tab()
  7217. # Clear project filename
  7218. self.app.project_filename = None
  7219. # Load the application defaults
  7220. self.defaults.load(filename=os.path.join(self.app.data_path, 'current_defaults.FlatConfig'), inform=self.inform)
  7221. # Re-fresh project options
  7222. self.app.on_options_app2project()
  7223. # Init FlatCAMTools
  7224. self.app.init_tools()
  7225. # Try to close all tabs in the PlotArea but only if the appGUI is active (CLI is None)
  7226. if cli is None:
  7227. # we need to go in reverse because once we remove a tab then the index changes
  7228. # meaning that removing the first tab (idx = 0) then the tab at former idx = 1 will assume idx = 0
  7229. # and so on. Therefore the deletion should be done in reverse
  7230. wdg_count = self.app.ui.plot_tab_area.tabBar.count() - 1
  7231. for index in range(wdg_count, -1, -1):
  7232. try:
  7233. self.app.ui.plot_tab_area.closeTab(index)
  7234. except Exception as e:
  7235. log.debug("App.on_file_new() --> %s" % str(e))
  7236. # # And then add again the Plot Area
  7237. self.app.ui.plot_tab_area.insertTab(0, self.app.ui.plot_tab, _("Plot Area"))
  7238. self.app.ui.plot_tab_area.protectTab(0)
  7239. # take the focus of the Notebook on Project Tab.
  7240. self.app.ui.notebook.setCurrentWidget(self.app.ui.project_tab)
  7241. self.app.set_ui_title(name=_("New Project - Not saved"))
  7242. def on_filenewscript(self, silent=False):
  7243. """
  7244. Will create a new script file and open it in the Code Editor
  7245. :param silent: if True will not display status messages
  7246. :return: None
  7247. """
  7248. if silent is False:
  7249. self.inform.emit('[success] %s' % _("New TCL script file created in Code Editor."))
  7250. # hide coordinates toolbars in the infobar while in DB
  7251. self.app.ui.coords_toolbar.hide()
  7252. self.app.ui.delta_coords_toolbar.hide()
  7253. self.app.app_obj.new_script_object()
  7254. def on_fileopenscript(self, name=None, silent=False):
  7255. """
  7256. Will open a Tcl script file into the Code Editor
  7257. :param silent: if True will not display status messages
  7258. :param name: name of a Tcl script file to open
  7259. :return: None
  7260. """
  7261. self.app.log.debug("on_fileopenscript()")
  7262. _filter_ = "TCL script .FlatScript (*.FlatScript);;TCL script .tcl (*.TCL);;TCL script .txt (*.TXT);;" \
  7263. "All Files (*.*)"
  7264. if name:
  7265. filenames = [name]
  7266. else:
  7267. try:
  7268. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(
  7269. caption=_("Open TCL script"), directory=self.app.get_last_folder(), filter=_filter_)
  7270. except TypeError:
  7271. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open TCL script"), filter=_filter_)
  7272. if len(filenames) == 0:
  7273. if silent is False:
  7274. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  7275. else:
  7276. for filename in filenames:
  7277. if filename != '':
  7278. self.worker_task.emit({'fcn': self.open_script, 'params': [filename]})
  7279. def on_fileopenscript_example(self, name=None, silent=False):
  7280. """
  7281. Will open a Tcl script file into the Code Editor
  7282. :param silent: if True will not display status messages
  7283. :param name: name of a Tcl script file to open
  7284. :return:
  7285. """
  7286. self.app.log.debug("on_fileopenscript_example()")
  7287. _filter_ = "TCL script .FlatScript (*.FlatScript);;TCL script .tcl (*.TCL);;TCL script .txt (*.TXT);;" \
  7288. "All Files (*.*)"
  7289. # test if the app was frozen and choose the path for the configuration file
  7290. if getattr(sys, "frozen", False) is True:
  7291. example_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\assets\\examples'
  7292. else:
  7293. example_path = os.path.dirname(os.path.realpath(__file__)) + '\\assets\\examples'
  7294. if name:
  7295. filenames = [name]
  7296. else:
  7297. try:
  7298. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(
  7299. caption=_("Open TCL script"), directory=example_path, filter=_filter_)
  7300. except TypeError:
  7301. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open TCL script"), filter=_filter_)
  7302. if len(filenames) == 0:
  7303. if silent is False:
  7304. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  7305. else:
  7306. for filename in filenames:
  7307. if filename != '':
  7308. self.worker_task.emit({'fcn': self.open_script, 'params': [filename]})
  7309. def on_filerunscript(self, name=None, silent=False):
  7310. """
  7311. File menu callback for loading and running a TCL script.
  7312. :param silent: if True will not display status messages
  7313. :param name: name of a Tcl script file to be run by FlatCAM
  7314. :return: None
  7315. """
  7316. self.app.log.debug("on_file_runscript()")
  7317. if name:
  7318. filename = name
  7319. if self.app.cmd_line_headless != 1:
  7320. self.splash.showMessage('%s: %ssec\n%s' %
  7321. (_("Canvas initialization started.\n"
  7322. "Canvas initialization finished in"), '%.2f' % self.app.used_time,
  7323. _("Executing ScriptObject file.")
  7324. ),
  7325. alignment=Qt.AlignBottom | Qt.AlignLeft,
  7326. color=QtGui.QColor("gray"))
  7327. else:
  7328. _filter_ = "TCL script .FlatScript (*.FlatScript);;TCL script .tcl (*.TCL);;TCL script .txt (*.TXT);;" \
  7329. "All Files (*.*)"
  7330. try:
  7331. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Run TCL script"),
  7332. directory=self.app.get_last_folder(),
  7333. filter=_filter_)
  7334. except TypeError:
  7335. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Run TCL script"), filter=_filter_)
  7336. # The Qt methods above will return a QString which can cause problems later.
  7337. # So far json.dump() will fail to serialize it.
  7338. filename = str(filename)
  7339. if filename == "":
  7340. if silent is False:
  7341. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  7342. else:
  7343. if self.app.cmd_line_headless != 1:
  7344. if self.app.ui.shell_dock.isHidden():
  7345. self.app.ui.shell_dock.show()
  7346. try:
  7347. with open(filename, "r") as tcl_script:
  7348. cmd_line_shellfile_content = tcl_script.read()
  7349. if self.app.cmd_line_headless != 1:
  7350. self.app.shell.exec_command(cmd_line_shellfile_content)
  7351. else:
  7352. self.app.shell.exec_command(cmd_line_shellfile_content, no_echo=True)
  7353. if silent is False:
  7354. self.inform.emit('[success] %s' % _("TCL script file opened in Code Editor and executed."))
  7355. except Exception as e:
  7356. self.app.debug("App.on_filerunscript() -> %s" % str(e))
  7357. sys.exit(2)
  7358. def on_file_saveproject(self, silent=False):
  7359. """
  7360. Callback for menu item File->Save Project. Saves the project to
  7361. ``self.project_filename`` or calls ``self.on_file_saveprojectas()``
  7362. if set to None. The project is saved by calling ``self.save_project()``.
  7363. :param silent: if True will not display status messages
  7364. :return: None
  7365. """
  7366. if self.app.project_filename is None:
  7367. self.on_file_saveprojectas()
  7368. else:
  7369. self.worker_task.emit({'fcn': self.save_project, 'params': [self.app.project_filename, silent]})
  7370. if self.defaults["global_open_style"] is False:
  7371. self.app.file_opened.emit("project", self.project_filename)
  7372. self.app.file_saved.emit("project", self.project_filename)
  7373. self.app.set_ui_title(name=self.app.project_filename)
  7374. self.app.should_we_save = False
  7375. def on_file_saveprojectas(self, make_copy=False, use_thread=True, quit_action=False):
  7376. """
  7377. Callback for menu item File->Save Project As... Opens a file
  7378. chooser and saves the project to the given file via
  7379. ``self.save_project()``.
  7380. :param make_copy if to be create a copy of the project; boolean
  7381. :param use_thread: if to be run in a separate thread; boolean
  7382. :param quit_action: if to be followed by quiting the application; boolean
  7383. :return: None
  7384. """
  7385. date = str(datetime.today()).rpartition('.')[0]
  7386. date = ''.join(c for c in date if c not in ':-')
  7387. date = self.date.replace(' ', '_')
  7388. filter_ = "FlatCAM Project .FlatPrj (*.FlatPrj);; All Files (*.*)"
  7389. try:
  7390. filename, _f = FCFileSaveDialog.get_saved_filename(
  7391. caption=_("Save Project As ..."),
  7392. directory='{l_save}/{proj}_{date}'.format(l_save=str(self.app.get_last_save_folder()), date=date,
  7393. proj=_("Project")),
  7394. ext_filter=filter_
  7395. )
  7396. except TypeError:
  7397. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Project As ..."), ext_filter=filter_)
  7398. filename = str(filename)
  7399. if filename == '':
  7400. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  7401. return
  7402. if use_thread is True:
  7403. self.worker_task.emit({'fcn': self.save_project, 'params': [filename, quit_action]})
  7404. else:
  7405. self.save_project(filename, quit_action)
  7406. # self.save_project(filename)
  7407. if self.defaults["global_open_style"] is False:
  7408. self.app.file_opened.emit("project", filename)
  7409. self.app.file_saved.emit("project", filename)
  7410. if not make_copy:
  7411. self.app.project_filename = filename
  7412. self.app.set_ui_title(name=self.app.project_filename)
  7413. self.app.should_we_save = False
  7414. def on_file_save_objects_pdf(self, use_thread=True):
  7415. date = str(datetime.today()).rpartition('.')[0]
  7416. date = ''.join(c for c in date if c not in ':-')
  7417. date = date.replace(' ', '_')
  7418. try:
  7419. obj_selection = self.app.collection.get_selected()
  7420. if len(obj_selection) == 1:
  7421. obj_name = str(obj_selection[0].options['name'])
  7422. else:
  7423. obj_name = _("FlatCAM objects print")
  7424. except AttributeError as err:
  7425. self.app.log.debug("App.on_file_save_object_pdf() --> %s" % str(err))
  7426. self.inform.emit('[ERROR_NOTCL] %s' % _("No object selected."))
  7427. return
  7428. if not obj_selection:
  7429. self.inform.emit('[ERROR_NOTCL] %s' % _("No object selected."))
  7430. return
  7431. filter_ = "PDF File .pdf (*.PDF);; All Files (*.*)"
  7432. try:
  7433. filename, _f = FCFileSaveDialog.get_saved_filename(
  7434. caption=_("Save Object as PDF ..."),
  7435. directory='{l_save}/{obj_name}_{date}'.format(l_save=str(self.app.get_last_save_folder()),
  7436. obj_name=obj_name,
  7437. date=date),
  7438. ext_filter=filter_
  7439. )
  7440. except TypeError:
  7441. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Object as PDF ..."), ext_filter=filter_)
  7442. filename = str(filename)
  7443. if filename == '':
  7444. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  7445. return
  7446. if use_thread is True:
  7447. self.app.proc_container.new(_("Printing PDF ... Please wait."))
  7448. self.worker_task.emit({'fcn': self.save_pdf, 'params': [filename, obj_selection]})
  7449. else:
  7450. self.save_pdf(filename, obj_selection)
  7451. # self.save_project(filename)
  7452. if self.defaults["global_open_style"] is False:
  7453. self.app.file_opened.emit("pdf", filename)
  7454. self.app.file_saved.emit("pdf", filename)
  7455. def save_pdf(self, file_name, obj_selection):
  7456. p_size = self.defaults['global_workspaceT']
  7457. orientation = self.defaults['global_workspace_orientation']
  7458. color = 'black'
  7459. transparency_level = 1.0
  7460. self.pagesize.update(
  7461. {
  7462. 'Bounds': None,
  7463. 'A0': (841 * mm, 1189 * mm),
  7464. 'A1': (594 * mm, 841 * mm),
  7465. 'A2': (420 * mm, 594 * mm),
  7466. 'A3': (297 * mm, 420 * mm),
  7467. 'A4': (210 * mm, 297 * mm),
  7468. 'A5': (148 * mm, 210 * mm),
  7469. 'A6': (105 * mm, 148 * mm),
  7470. 'A7': (74 * mm, 105 * mm),
  7471. 'A8': (52 * mm, 74 * mm),
  7472. 'A9': (37 * mm, 52 * mm),
  7473. 'A10': (26 * mm, 37 * mm),
  7474. 'B0': (1000 * mm, 1414 * mm),
  7475. 'B1': (707 * mm, 1000 * mm),
  7476. 'B2': (500 * mm, 707 * mm),
  7477. 'B3': (353 * mm, 500 * mm),
  7478. 'B4': (250 * mm, 353 * mm),
  7479. 'B5': (176 * mm, 250 * mm),
  7480. 'B6': (125 * mm, 176 * mm),
  7481. 'B7': (88 * mm, 125 * mm),
  7482. 'B8': (62 * mm, 88 * mm),
  7483. 'B9': (44 * mm, 62 * mm),
  7484. 'B10': (31 * mm, 44 * mm),
  7485. 'C0': (917 * mm, 1297 * mm),
  7486. 'C1': (648 * mm, 917 * mm),
  7487. 'C2': (458 * mm, 648 * mm),
  7488. 'C3': (324 * mm, 458 * mm),
  7489. 'C4': (229 * mm, 324 * mm),
  7490. 'C5': (162 * mm, 229 * mm),
  7491. 'C6': (114 * mm, 162 * mm),
  7492. 'C7': (81 * mm, 114 * mm),
  7493. 'C8': (57 * mm, 81 * mm),
  7494. 'C9': (40 * mm, 57 * mm),
  7495. 'C10': (28 * mm, 40 * mm),
  7496. # American paper sizes
  7497. 'LETTER': (8.5 * inch, 11 * inch),
  7498. 'LEGAL': (8.5 * inch, 14 * inch),
  7499. 'ELEVENSEVENTEEN': (11 * inch, 17 * inch),
  7500. # From https://en.wikipedia.org/wiki/Paper_size
  7501. 'JUNIOR_LEGAL': (5 * inch, 8 * inch),
  7502. 'HALF_LETTER': (5.5 * inch, 8 * inch),
  7503. 'GOV_LETTER': (8 * inch, 10.5 * inch),
  7504. 'GOV_LEGAL': (8.5 * inch, 13 * inch),
  7505. 'LEDGER': (17 * inch, 11 * inch),
  7506. }
  7507. )
  7508. exported_svg = []
  7509. for obj in obj_selection:
  7510. svg_obj = obj.export_svg(scale_stroke_factor=0.0, scale_factor_x=None, scale_factor_y=None,
  7511. skew_factor_x=None, skew_factor_y=None, mirror=None)
  7512. if obj.kind.lower() == 'gerber' or obj.kind.lower() == 'excellon':
  7513. color = obj.fill_color[:-2]
  7514. transparency_level = obj.fill_color[-2:]
  7515. elif obj.kind.lower() == 'geometry':
  7516. color = self.defaults["global_draw_color"]
  7517. # Change the attributes of the exported SVG
  7518. # We don't need stroke-width
  7519. # We set opacity to maximum
  7520. # We set the colour to WHITE
  7521. root = ET.fromstring(svg_obj)
  7522. for child in root:
  7523. child.set('fill', str(color))
  7524. child.set('opacity', str(transparency_level))
  7525. child.set('stroke', str(color))
  7526. exported_svg.append(ET.tostring(root))
  7527. xmin = Inf
  7528. ymin = Inf
  7529. xmax = -Inf
  7530. ymax = -Inf
  7531. for obj in obj_selection:
  7532. try:
  7533. gxmin, gymin, gxmax, gymax = obj.bounds()
  7534. xmin = min([xmin, gxmin])
  7535. ymin = min([ymin, gymin])
  7536. xmax = max([xmax, gxmax])
  7537. ymax = max([ymax, gymax])
  7538. except Exception as e:
  7539. self.app.log.warning(
  7540. "DEV WARNING: Tried to get bounds of empty geometry in App.save_pdf(). %s" % str(e))
  7541. # Determine bounding area for svg export
  7542. bounds = [xmin, ymin, xmax, ymax]
  7543. size = bounds[2] - bounds[0], bounds[3] - bounds[1]
  7544. # This contain the measure units
  7545. uom = obj_selection[0].units.lower()
  7546. # Define a boundary around SVG of about 1.0mm (~39mils)
  7547. if uom in "mm":
  7548. boundary = 1.0
  7549. else:
  7550. boundary = 0.0393701
  7551. # Convert everything to strings for use in the xml doc
  7552. svgwidth = str(size[0] + (2 * boundary))
  7553. svgheight = str(size[1] + (2 * boundary))
  7554. minx = str(bounds[0] - boundary)
  7555. miny = str(bounds[1] + boundary + size[1])
  7556. # Add a SVG Header and footer to the svg output from shapely
  7557. # The transform flips the Y Axis so that everything renders
  7558. # properly within svg apps such as inkscape
  7559. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  7560. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  7561. svg_header += 'width="' + svgwidth + uom + '" '
  7562. svg_header += 'height="' + svgheight + uom + '" '
  7563. svg_header += 'viewBox="' + minx + ' -' + miny + ' ' + svgwidth + ' ' + svgheight + '" '
  7564. svg_header += '>'
  7565. svg_header += '<g transform="scale(1,-1)">'
  7566. svg_footer = '</g> </svg>'
  7567. svg_elem = str(svg_header)
  7568. for svg_item in exported_svg:
  7569. svg_elem += str(svg_item)
  7570. svg_elem += str(svg_footer)
  7571. # Parse the xml through a xml parser just to add line feeds
  7572. # and to make it look more pretty for the output
  7573. doc = parse_xml_string(svg_elem)
  7574. doc_final = doc.toprettyxml()
  7575. try:
  7576. if self.defaults['units'].upper() == 'IN':
  7577. unit = inch
  7578. else:
  7579. unit = mm
  7580. doc_final = StringIO(doc_final)
  7581. drawing = svg2rlg(doc_final)
  7582. if p_size == 'Bounds':
  7583. renderPDF.drawToFile(drawing, file_name)
  7584. else:
  7585. if orientation == 'p':
  7586. page_size = portrait(self.pagesize[p_size])
  7587. else:
  7588. page_size = landscape(self.pagesize[p_size])
  7589. my_canvas = canvas.Canvas(file_name, pagesize=page_size)
  7590. my_canvas.translate(bounds[0] * unit, bounds[1] * unit)
  7591. renderPDF.draw(drawing, my_canvas, 0, 0)
  7592. my_canvas.save()
  7593. except Exception as e:
  7594. self.app.log.debug("MenuFileHandlers.save_pdf() --> PDF output --> %s" % str(e))
  7595. return 'fail'
  7596. self.inform.emit('[success] %s: %s' % (_("PDF file saved to"), file_name))
  7597. def export_svg(self, obj_name, filename, scale_stroke_factor=0.00):
  7598. """
  7599. Exports a Geometry Object to an SVG file.
  7600. :param obj_name: the name of the FlatCAM object to be saved as SVG
  7601. :param filename: Path to the SVG file to save to.
  7602. :param scale_stroke_factor: factor by which to change/scale the thickness of the features
  7603. :return:
  7604. """
  7605. if filename is None:
  7606. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  7607. is not None else self.defaults["global_last_folder"]
  7608. self.app.log.debug("export_svg()")
  7609. try:
  7610. obj = self.app.collection.get_by_name(str(obj_name))
  7611. except Exception:
  7612. return 'fail'
  7613. with self.app.proc_container.new(_("Exporting SVG")) as proc:
  7614. exported_svg = obj.export_svg(scale_stroke_factor=scale_stroke_factor)
  7615. # Determine bounding area for svg export
  7616. bounds = obj.bounds()
  7617. size = obj.size()
  7618. # Convert everything to strings for use in the xml doc
  7619. svgwidth = str(size[0])
  7620. svgheight = str(size[1])
  7621. minx = str(bounds[0])
  7622. miny = str(bounds[1] - size[1])
  7623. uom = obj.units.lower()
  7624. # Add a SVG Header and footer to the svg output from shapely
  7625. # The transform flips the Y Axis so that everything renders
  7626. # properly within svg apps such as inkscape
  7627. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  7628. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  7629. svg_header += 'width="' + svgwidth + uom + '" '
  7630. svg_header += 'height="' + svgheight + uom + '" '
  7631. svg_header += 'viewBox="' + minx + ' ' + miny + ' ' + svgwidth + ' ' + svgheight + '">'
  7632. svg_header += '<g transform="scale(1,-1)">'
  7633. svg_footer = '</g> </svg>'
  7634. svg_elem = svg_header + exported_svg + svg_footer
  7635. # Parse the xml through a xml parser just to add line feeds
  7636. # and to make it look more pretty for the output
  7637. svgcode = parse_xml_string(svg_elem)
  7638. svgcode = svgcode.toprettyxml()
  7639. try:
  7640. with open(filename, 'w') as fp:
  7641. fp.write(svgcode)
  7642. except PermissionError:
  7643. self.inform.emit('[WARNING] %s' %
  7644. _("Permission denied, saving not possible.\n"
  7645. "Most likely another app is holding the file open and not accessible."))
  7646. return 'fail'
  7647. if self.defaults["global_open_style"] is False:
  7648. self.app.file_opened.emit("SVG", filename)
  7649. self.app.file_saved.emit("SVG", filename)
  7650. self.inform.emit('[success] %s: %s' % (_("SVG file exported to"), filename))
  7651. def on_import_preferences(self):
  7652. """
  7653. Loads the application default settings from a saved file into
  7654. ``self.defaults`` dictionary.
  7655. :return: None
  7656. """
  7657. self.app.log.debug("App.on_import_preferences()")
  7658. # Show file chooser
  7659. filter_ = "Config File (*.FlatConfig);;All Files (*.*)"
  7660. try:
  7661. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import FlatCAM Preferences"),
  7662. directory=self.app.data_path,
  7663. filter=filter_)
  7664. except TypeError:
  7665. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import FlatCAM Preferences"),
  7666. filter=filter_)
  7667. filename = str(filename)
  7668. if filename == "":
  7669. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  7670. return
  7671. # Load in the defaults from the chosen file
  7672. self.defaults.load(filename=filename, inform=self.inform)
  7673. self.app.preferencesUiManager.on_preferences_edited()
  7674. self.inform.emit('[success] %s: %s' % (_("Imported Defaults from"), filename))
  7675. def on_export_preferences(self):
  7676. """
  7677. Save the defaults dictionary to a file.
  7678. :return: None
  7679. """
  7680. self.app.log.debug("on_export_preferences()")
  7681. # defaults_file_content = None
  7682. # Show file chooser
  7683. date = str(datetime.today()).rpartition('.')[0]
  7684. date = ''.join(c for c in date if c not in ':-')
  7685. date = date.replace(' ', '_')
  7686. filter__ = "Config File .FlatConfig (*.FlatConfig);;All Files (*.*)"
  7687. try:
  7688. filename, _f = FCFileSaveDialog.get_saved_filename(
  7689. caption=_("Export FlatCAM Preferences"),
  7690. directory=self.app.data_path + '/preferences_' + date,
  7691. ext_filter=filter__
  7692. )
  7693. except TypeError:
  7694. filename, _f = FCFileSaveDialog.get_saved_filename(
  7695. caption=_("Export FlatCAM Preferences"), ext_filter=filter__)
  7696. filename = str(filename)
  7697. if filename == "":
  7698. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  7699. return 'fail'
  7700. # Update options
  7701. self.app.preferencesUiManager.defaults_read_form()
  7702. self.defaults.propagate_defaults()
  7703. # Save update options
  7704. try:
  7705. self.defaults.write(filename=filename)
  7706. except Exception:
  7707. self.inform.emit('[ERROR_NOTCL] %s %s' % (_("Failed to write defaults to file."), str(filename)))
  7708. return
  7709. if self.defaults["global_open_style"] is False:
  7710. self.app.file_opened.emit("preferences", filename)
  7711. self.app.file_saved.emit("preferences", filename)
  7712. self.inform.emit('[success] %s: %s' % (_("Exported preferences to"), filename))
  7713. def export_excellon(self, obj_name, filename, local_use=None, use_thread=True):
  7714. """
  7715. Exports a Excellon Object to an Excellon file.
  7716. :param obj_name: the name of the FlatCAM object to be saved as Excellon
  7717. :param filename: Path to the Excellon file to save to.
  7718. :param local_use:
  7719. :param use_thread: if to be run in a separate thread
  7720. :return:
  7721. """
  7722. if filename is None:
  7723. if self.defaults["global_last_save_folder"]:
  7724. filename = self.defaults["global_last_save_folder"] + '/' + 'exported_excellon'
  7725. else:
  7726. filename = self.defaults["global_last_folder"] + '/' + 'exported_excellon'
  7727. self.app.log.debug("export_excellon()")
  7728. format_exc = ';FILE_FORMAT=%d:%d\n' % (self.defaults["excellon_exp_integer"],
  7729. self.defaults["excellon_exp_decimals"]
  7730. )
  7731. if local_use is None:
  7732. try:
  7733. obj = self.app.collection.get_by_name(str(obj_name))
  7734. except Exception:
  7735. return "Could not retrieve object: %s" % obj_name
  7736. else:
  7737. obj = local_use
  7738. if not isinstance(obj, ExcellonObject):
  7739. self.inform.emit('[ERROR_NOTCL] %s' %
  7740. _("Failed. Only Excellon objects can be saved as Excellon files..."))
  7741. return
  7742. # updated units
  7743. eunits = self.defaults["excellon_exp_units"]
  7744. ewhole = self.defaults["excellon_exp_integer"]
  7745. efract = self.defaults["excellon_exp_decimals"]
  7746. ezeros = self.defaults["excellon_exp_zeros"]
  7747. eformat = self.defaults["excellon_exp_format"]
  7748. slot_type = self.defaults["excellon_exp_slot_type"]
  7749. fc_units = self.defaults['units'].upper()
  7750. if fc_units == 'MM':
  7751. factor = 1 if eunits == 'METRIC' else 0.03937
  7752. else:
  7753. factor = 25.4 if eunits == 'METRIC' else 1
  7754. def make_excellon():
  7755. try:
  7756. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  7757. header = 'M48\n'
  7758. header += ';EXCELLON GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s\n' % \
  7759. (str(self.app.version), str(self.app.version_date))
  7760. header += ';Filename: %s' % str(obj_name) + '\n'
  7761. header += ';Created on : %s' % time_str + '\n'
  7762. if eformat == 'dec':
  7763. has_slots, excellon_code = obj.export_excellon(ewhole, efract, factor=factor, slot_type=slot_type)
  7764. header += eunits + '\n'
  7765. for tool in obj.tools:
  7766. if eunits == 'METRIC':
  7767. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['tooldia']) * factor,
  7768. tool=str(tool),
  7769. dec=2)
  7770. else:
  7771. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['tooldia']) * factor,
  7772. tool=str(tool),
  7773. dec=4)
  7774. else:
  7775. if ezeros == 'LZ':
  7776. has_slots, excellon_code = obj.export_excellon(ewhole, efract,
  7777. form='ndec', e_zeros='LZ', factor=factor,
  7778. slot_type=slot_type)
  7779. header += '%s,%s\n' % (eunits, 'LZ')
  7780. header += format_exc
  7781. for tool in obj.tools:
  7782. if eunits == 'METRIC':
  7783. header += "T{tool}F00S00C{:.{dec}f}\n".format(
  7784. float(obj.tools[tool]['tooldia']) * factor,
  7785. tool=str(tool),
  7786. dec=2)
  7787. else:
  7788. header += "T{tool}F00S00C{:.{dec}f}\n".format(
  7789. float(obj.tools[tool]['tooldia']) * factor,
  7790. tool=str(tool),
  7791. dec=4)
  7792. else:
  7793. has_slots, excellon_code = obj.export_excellon(ewhole, efract,
  7794. form='ndec', e_zeros='TZ', factor=factor,
  7795. slot_type=slot_type)
  7796. header += '%s,%s\n' % (eunits, 'TZ')
  7797. header += format_exc
  7798. for tool in obj.tools:
  7799. if eunits == 'METRIC':
  7800. header += "T{tool}F00S00C{:.{dec}f}\n".format(
  7801. float(obj.tools[tool]['tooldia']) * factor,
  7802. tool=str(tool),
  7803. dec=2)
  7804. else:
  7805. header += "T{tool}F00S00C{:.{dec}f}\n".format(
  7806. float(obj.tools[tool]['tooldia']) * factor,
  7807. tool=str(tool),
  7808. dec=4)
  7809. header += '%\n'
  7810. footer = 'M30\n'
  7811. exported_excellon = header
  7812. exported_excellon += excellon_code
  7813. exported_excellon += footer
  7814. if local_use is None:
  7815. try:
  7816. with open(filename, 'w') as fp:
  7817. fp.write(exported_excellon)
  7818. except PermissionError:
  7819. self.inform.emit('[WARNING] %s' %
  7820. _("Permission denied, saving not possible.\n"
  7821. "Most likely another app is holding the file open and not accessible."))
  7822. return 'fail'
  7823. if self.defaults["global_open_style"] is False:
  7824. self.app.file_opened.emit("Excellon", filename)
  7825. self.app.file_saved.emit("Excellon", filename)
  7826. self.inform.emit('[success] %s: %s' % (_("Excellon file exported to"), filename))
  7827. else:
  7828. return exported_excellon
  7829. except Exception as e:
  7830. self.app.log.debug("App.export_excellon.make_excellon() --> %s" % str(e))
  7831. return 'fail'
  7832. if use_thread is True:
  7833. with self.app.proc_container.new(_("Exporting Excellon")) as proc:
  7834. def job_thread_exc(app_obj):
  7835. ret = make_excellon()
  7836. if ret == 'fail':
  7837. self.inform.emit('[ERROR_NOTCL] %s' % _('Could not export Excellon file.'))
  7838. return
  7839. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  7840. else:
  7841. eret = make_excellon()
  7842. if eret == 'fail':
  7843. self.inform.emit('[ERROR_NOTCL] %s' % _('Could not export Excellon file.'))
  7844. return 'fail'
  7845. if local_use is not None:
  7846. return eret
  7847. def export_gerber(self, obj_name, filename, local_use=None, use_thread=True):
  7848. """
  7849. Exports a Gerber Object to an Gerber file.
  7850. :param obj_name: the name of the FlatCAM object to be saved as Gerber
  7851. :param filename: Path to the Gerber file to save to.
  7852. :param local_use: if the Gerber code is to be saved to a file (None) or used within FlatCAM.
  7853. When not None, the value will be the actual Gerber object for which to create
  7854. the Gerber code
  7855. :param use_thread: if to be run in a separate thread
  7856. :return:
  7857. """
  7858. if filename is None:
  7859. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  7860. is not None else self.defaults["global_last_folder"]
  7861. self.app.log.debug("export_gerber()")
  7862. if local_use is None:
  7863. try:
  7864. obj = self.app.collection.get_by_name(str(obj_name))
  7865. except Exception:
  7866. return 'fail'
  7867. else:
  7868. obj = local_use
  7869. # updated units
  7870. gunits = self.defaults["gerber_exp_units"]
  7871. gwhole = self.defaults["gerber_exp_integer"]
  7872. gfract = self.defaults["gerber_exp_decimals"]
  7873. gzeros = self.defaults["gerber_exp_zeros"]
  7874. fc_units = self.defaults['units'].upper()
  7875. if fc_units == 'MM':
  7876. factor = 1 if gunits == 'MM' else 0.03937
  7877. else:
  7878. factor = 25.4 if gunits == 'MM' else 1
  7879. def make_gerber():
  7880. try:
  7881. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  7882. header = 'G04*\n'
  7883. header += 'G04 RS-274X GERBER GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s*\n' % \
  7884. (str(self.app.version), str(self.app.version_date))
  7885. header += 'G04 Filename: %s*' % str(obj_name) + '\n'
  7886. header += 'G04 Created on : %s*' % time_str + '\n'
  7887. header += '%%FS%sAX%s%sY%s%s*%%\n' % (gzeros, gwhole, gfract, gwhole, gfract)
  7888. header += "%MO{units}*%\n".format(units=gunits)
  7889. for apid in obj.apertures:
  7890. if obj.apertures[apid]['type'] == 'C':
  7891. header += "%ADD{apid}{type},{size}*%\n".format(
  7892. apid=str(apid),
  7893. type='C',
  7894. size=(factor * obj.apertures[apid]['size'])
  7895. )
  7896. elif obj.apertures[apid]['type'] == 'R':
  7897. header += "%ADD{apid}{type},{width}X{height}*%\n".format(
  7898. apid=str(apid),
  7899. type='R',
  7900. width=(factor * obj.apertures[apid]['width']),
  7901. height=(factor * obj.apertures[apid]['height'])
  7902. )
  7903. elif obj.apertures[apid]['type'] == 'O':
  7904. header += "%ADD{apid}{type},{width}X{height}*%\n".format(
  7905. apid=str(apid),
  7906. type='O',
  7907. width=(factor * obj.apertures[apid]['width']),
  7908. height=(factor * obj.apertures[apid]['height'])
  7909. )
  7910. header += '\n'
  7911. # obsolete units but some software may need it
  7912. if gunits == 'IN':
  7913. header += 'G70*\n'
  7914. else:
  7915. header += 'G71*\n'
  7916. # Absolute Mode
  7917. header += 'G90*\n'
  7918. header += 'G01*\n'
  7919. # positive polarity
  7920. header += '%LPD*%\n'
  7921. footer = 'M02*\n'
  7922. gerber_code = obj.export_gerber(gwhole, gfract, g_zeros=gzeros, factor=factor)
  7923. exported_gerber = header
  7924. exported_gerber += gerber_code
  7925. exported_gerber += footer
  7926. if local_use is None:
  7927. try:
  7928. with open(filename, 'w') as fp:
  7929. fp.write(exported_gerber)
  7930. except PermissionError:
  7931. self.inform.emit('[WARNING] %s' %
  7932. _("Permission denied, saving not possible.\n"
  7933. "Most likely another app is holding the file open and not accessible."))
  7934. return 'fail'
  7935. if self.defaults["global_open_style"] is False:
  7936. self.app.file_opened.emit("Gerber", filename)
  7937. self.app.file_saved.emit("Gerber", filename)
  7938. self.inform.emit('[success] %s: %s' % (_("Gerber file exported to"), filename))
  7939. else:
  7940. return exported_gerber
  7941. except Exception as e:
  7942. log.debug("App.export_gerber.make_gerber() --> %s" % str(e))
  7943. return 'fail'
  7944. if use_thread is True:
  7945. with self.app.proc_container.new(_("Exporting Gerber")) as proc:
  7946. def job_thread_grb(app_obj):
  7947. ret = make_gerber()
  7948. if ret == 'fail':
  7949. self.inform.emit('[ERROR_NOTCL] %s' % _('Could not export file.'))
  7950. return
  7951. self.worker_task.emit({'fcn': job_thread_grb, 'params': [self]})
  7952. else:
  7953. gret = make_gerber()
  7954. if gret == 'fail':
  7955. self.inform.emit('[ERROR_NOTCL] %s' % _('Could not export file.'))
  7956. return 'fail'
  7957. if local_use is not None:
  7958. return gret
  7959. def export_dxf(self, obj_name, filename, local_use=None, use_thread=True):
  7960. """
  7961. Exports a Geometry Object to an DXF file.
  7962. :param obj_name: the name of the FlatCAM object to be saved as DXF
  7963. :param filename: Path to the DXF file to save to.
  7964. :param local_use: if the Gerber code is to be saved to a file (None) or used within FlatCAM.
  7965. When not None, the value will be the actual Geometry object for which to create
  7966. the Geometry/DXF code
  7967. :param use_thread: if to be run in a separate thread
  7968. :return:
  7969. """
  7970. if filename is None:
  7971. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  7972. is not None else self.defaults["global_last_folder"]
  7973. self.app.log.debug("export_dxf()")
  7974. if local_use is None:
  7975. try:
  7976. obj = self.app.collection.get_by_name(str(obj_name))
  7977. except Exception:
  7978. return 'fail'
  7979. else:
  7980. obj = local_use
  7981. def make_dxf():
  7982. try:
  7983. dxf_code = obj.export_dxf()
  7984. if local_use is None:
  7985. try:
  7986. dxf_code.saveas(filename)
  7987. except PermissionError:
  7988. self.inform.emit('[WARNING] %s' %
  7989. _("Permission denied, saving not possible.\n"
  7990. "Most likely another app is holding the file open and not accessible."))
  7991. return 'fail'
  7992. if self.defaults["global_open_style"] is False:
  7993. self.app.file_opened.emit("DXF", filename)
  7994. self.app.file_saved.emit("DXF", filename)
  7995. self.inform.emit('[success] %s: %s' % (_("DXF file exported to"), filename))
  7996. else:
  7997. return dxf_code
  7998. except Exception as e:
  7999. log.debug("App.export_dxf.make_dxf() --> %s" % str(e))
  8000. return 'fail'
  8001. if use_thread is True:
  8002. with self.app.proc_container.new(_("Exporting DXF")) as proc:
  8003. def job_thread_exc(app_obj):
  8004. ret_dxf_val = make_dxf()
  8005. if ret_dxf_val == 'fail':
  8006. app_obj.inform.emit('[WARNING_NOTCL] %s' % _('Could not export DXF file.'))
  8007. return
  8008. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  8009. else:
  8010. ret = make_dxf()
  8011. if ret == 'fail':
  8012. self.inform.emit('[WARNING_NOTCL] %s' % _('Could not export DXF file.'))
  8013. return
  8014. if local_use is not None:
  8015. return ret
  8016. def import_svg(self, filename, geo_type='geometry', outname=None, plot=True):
  8017. """
  8018. Adds a new Geometry Object to the projects and populates
  8019. it with shapes extracted from the SVG file.
  8020. :param plot: If True then the resulting object will be plotted on canvas
  8021. :param filename: Path to the SVG file.
  8022. :param geo_type: Type of FlatCAM object that will be created from SVG
  8023. :param outname: The name given to the resulting FlatCAM object
  8024. :return:
  8025. """
  8026. self.app.log.debug("App.import_svg()")
  8027. obj_type = ""
  8028. if geo_type is None or geo_type == "geometry":
  8029. obj_type = "geometry"
  8030. elif geo_type == "gerber":
  8031. obj_type = "gerber"
  8032. else:
  8033. self.inform.emit('[ERROR_NOTCL] %s' %
  8034. _("Not supported type is picked as parameter. Only Geometry and Gerber are supported"))
  8035. return
  8036. units = self.defaults['units'].upper()
  8037. def obj_init(geo_obj, app_obj):
  8038. geo_obj.import_svg(filename, obj_type, units=units)
  8039. geo_obj.multigeo = True
  8040. with open(filename) as f:
  8041. file_content = f.read()
  8042. geo_obj.source_file = file_content
  8043. with self.app.proc_container.new(_("Importing SVG")) as proc:
  8044. # Object name
  8045. name = outname or filename.split('/')[-1].split('\\')[-1]
  8046. ret = self.app.app_obj.new_object(obj_type, name, obj_init, autoselected=False, plot=plot)
  8047. if ret == 'fail':
  8048. self.inform.emit('[ERROR_NOTCL]%s' % _('Import failed.'))
  8049. return 'fail'
  8050. # Register recent file
  8051. self.app.file_opened.emit("svg", filename)
  8052. # appGUI feedback
  8053. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  8054. def import_dxf(self, filename, geo_type='geometry', outname=None, plot=True):
  8055. """
  8056. Adds a new Geometry Object to the projects and populates
  8057. it with shapes extracted from the DXF file.
  8058. :param filename: Path to the DXF file.
  8059. :param geo_type: Type of FlatCAM object that will be created from DXF
  8060. :param outname: Name for the imported Geometry
  8061. :param plot: If True then the resulting object will be plotted on canvas
  8062. :return:
  8063. """
  8064. self.app.log.debug(" ********* Importing DXF as: %s ********* " % geo_type.capitalize())
  8065. obj_type = ""
  8066. if geo_type is None or geo_type == "geometry":
  8067. obj_type = "geometry"
  8068. elif geo_type == "gerber":
  8069. obj_type = geo_type
  8070. else:
  8071. self.inform.emit('[ERROR_NOTCL] %s' %
  8072. _("Not supported type is picked as parameter. Only Geometry and Gerber are supported"))
  8073. return
  8074. units = self.defaults['units'].upper()
  8075. def obj_init(geo_obj, app_obj):
  8076. if obj_type == "geometry":
  8077. geo_obj.import_dxf_as_geo(filename, units=units)
  8078. elif obj_type == "gerber":
  8079. geo_obj.import_dxf_as_gerber(filename, units=units)
  8080. else:
  8081. return "fail"
  8082. geo_obj.multigeo = True
  8083. with open(filename) as f:
  8084. file_content = f.read()
  8085. geo_obj.source_file = file_content
  8086. with self.app.proc_container.new(_("Importing DXF")):
  8087. # Object name
  8088. name = outname or filename.split('/')[-1].split('\\')[-1]
  8089. ret = self.app.app_obj.new_object(obj_type, name, obj_init, autoselected=False, plot=plot)
  8090. if ret == 'fail':
  8091. self.inform.emit('[ERROR_NOTCL]%s' % _('Import failed.'))
  8092. return 'fail'
  8093. # Register recent file
  8094. self.app.file_opened.emit("dxf", filename)
  8095. # appGUI feedback
  8096. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  8097. def open_gerber(self, filename, outname=None, plot=True, from_tcl=False):
  8098. """
  8099. Opens a Gerber file, parses it and creates a new object for
  8100. it in the program. Thread-safe.
  8101. :param outname: Name of the resulting object. None causes the
  8102. name to be that of the file. Str.
  8103. :param filename: Gerber file filename
  8104. :type filename: str
  8105. :param plot: boolean, to plot or not the resulting object
  8106. :param from_tcl: True if run from Tcl Shell
  8107. :return: None
  8108. """
  8109. # How the object should be initialized
  8110. def obj_init(gerber_obj, app_obj):
  8111. assert isinstance(gerber_obj, GerberObject), \
  8112. "Expected to initialize a GerberObject but got %s" % type(gerber_obj)
  8113. # Opening the file happens here
  8114. try:
  8115. gerber_obj.parse_file(filename)
  8116. except IOError:
  8117. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open file"), filename))
  8118. return "fail"
  8119. except ParseError as err:
  8120. app_obj.inform.emit('[ERROR_NOTCL] %s: %s. %s' % (_("Failed to parse file"), filename, str(err)))
  8121. app_obj.log.error(str(err))
  8122. return "fail"
  8123. except Exception as e:
  8124. log.debug("App.open_gerber() --> %s" % str(e))
  8125. msg = '[ERROR] %s' % _("An internal error has occurred. See shell.\n")
  8126. msg += traceback.format_exc()
  8127. app_obj.inform.emit(msg)
  8128. return "fail"
  8129. if gerber_obj.is_empty():
  8130. app_obj.inform.emit('[ERROR_NOTCL] %s' %
  8131. _("Object is not Gerber file or empty. Aborting object creation."))
  8132. return "fail"
  8133. self.app.log.debug("open_gerber()")
  8134. with self.app.proc_container.new(_("Opening Gerber")):
  8135. # Object name
  8136. name = outname or filename.split('/')[-1].split('\\')[-1]
  8137. # # ## Object creation # ##
  8138. ret_val = self.app.app_obj.new_object("gerber", name, obj_init, autoselected=False, plot=plot)
  8139. if ret_val == 'fail':
  8140. if from_tcl:
  8141. filename = self.defaults['global_tcl_path'] + '/' + name
  8142. ret_val = self.app.app_obj.new_object("gerber", name, obj_init, autoselected=False, plot=plot)
  8143. if ret_val == 'fail':
  8144. self.inform.emit('[ERROR_NOTCL]%s' % _('Open Gerber failed. Probable not a Gerber file.'))
  8145. return 'fail'
  8146. # Register recent file
  8147. self.app.file_opened.emit("gerber", filename)
  8148. # appGUI feedback
  8149. self.app.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  8150. def open_excellon(self, filename, outname=None, plot=True, from_tcl=False):
  8151. """
  8152. Opens an Excellon file, parses it and creates a new object for
  8153. it in the program. Thread-safe.
  8154. :param outname: Name of the resulting object. None causes the name to be that of the file.
  8155. :param filename: Excellon file filename
  8156. :type filename: str
  8157. :param plot: boolean, to plot or not the resulting object
  8158. :param from_tcl: True if run from Tcl Shell
  8159. :return: None
  8160. """
  8161. self.app.log.debug("open_excellon()")
  8162. # How the object should be initialized
  8163. def obj_init(excellon_obj, app_obj):
  8164. try:
  8165. ret = excellon_obj.parse_file(filename=filename)
  8166. if ret == "fail":
  8167. app_obj.log.debug("Excellon parsing failed.")
  8168. self.inform.emit('[ERROR_NOTCL] %s' % _("This is not Excellon file."))
  8169. return "fail"
  8170. except IOError:
  8171. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Cannot open file"), filename))
  8172. app_obj.log.debug("Could not open Excellon object.")
  8173. return "fail"
  8174. except Exception:
  8175. msg = '[ERROR_NOTCL] %s' % _("An internal error has occurred. See shell.\n")
  8176. msg += traceback.format_exc()
  8177. app_obj.inform.emit(msg)
  8178. return "fail"
  8179. ret = excellon_obj.create_geometry()
  8180. if ret == 'fail':
  8181. app_obj.log.debug("Could not create geometry for Excellon object.")
  8182. return "fail"
  8183. for tool in excellon_obj.tools:
  8184. if excellon_obj.tools[tool]['solid_geometry']:
  8185. return
  8186. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("No geometry found in file"), filename))
  8187. return "fail"
  8188. with self.app.proc_container.new(_("Opening Excellon.")):
  8189. # Object name
  8190. name = outname or filename.split('/')[-1].split('\\')[-1]
  8191. ret_val = self.app.app_obj.new_object("excellon", name, obj_init, autoselected=False, plot=plot)
  8192. if ret_val == 'fail':
  8193. if from_tcl:
  8194. filename = self.defaults['global_tcl_path'] + '/' + name
  8195. ret_val = self.app.app_obj.new_object("excellon", name, obj_init, autoselected=False, plot=plot)
  8196. if ret_val == 'fail':
  8197. self.inform.emit('[ERROR_NOTCL] %s' %
  8198. _('Open Excellon file failed. Probable not an Excellon file.'))
  8199. return
  8200. # Register recent file
  8201. self.app.file_opened.emit("excellon", filename)
  8202. # appGUI feedback
  8203. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  8204. def open_gcode(self, filename, outname=None, force_parsing=None, plot=True, from_tcl=False):
  8205. """
  8206. Opens a G-gcode file, parses it and creates a new object for
  8207. it in the program. Thread-safe.
  8208. :param filename: G-code file filename
  8209. :param outname: Name of the resulting object. None causes the name to be that of the file.
  8210. :param force_parsing:
  8211. :param plot: If True plot the object on canvas
  8212. :param from_tcl: True if run from Tcl Shell
  8213. :return: None
  8214. """
  8215. self.app.log.debug("open_gcode()")
  8216. # How the object should be initialized
  8217. def obj_init(job_obj, app_obj_):
  8218. """
  8219. :param job_obj: the resulting object
  8220. :type app_obj_: App
  8221. """
  8222. assert isinstance(app_obj_, App), \
  8223. "Initializer expected App, got %s" % type(app_obj_)
  8224. app_obj_.inform.emit('%s...' % _("Reading GCode file"))
  8225. try:
  8226. f = open(filename)
  8227. gcode = f.read()
  8228. f.close()
  8229. except IOError:
  8230. app_obj_.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open"), filename))
  8231. return "fail"
  8232. job_obj.gcode = gcode
  8233. gcode_ret = job_obj.gcode_parse(force_parsing=force_parsing)
  8234. if gcode_ret == "fail":
  8235. self.inform.emit('[ERROR_NOTCL] %s' % _("This is not GCODE"))
  8236. return "fail"
  8237. job_obj.create_geometry()
  8238. with self.app.proc_container.new(_("Opening G-Code.")):
  8239. # Object name
  8240. name = outname or filename.split('/')[-1].split('\\')[-1]
  8241. # New object creation and file processing
  8242. ret_val = self.app.app_obj.new_object("cncjob", name, obj_init, autoselected=False, plot=plot)
  8243. if ret_val == 'fail':
  8244. if from_tcl:
  8245. filename = self.defaults['global_tcl_path'] + '/' + name
  8246. ret_val = self.app.app_obj.new_object("cncjob", name, obj_init, autoselected=False, plot=plot)
  8247. if ret_val == 'fail':
  8248. self.inform.emit('[ERROR_NOTCL] %s' %
  8249. _("Failed to create CNCJob Object. Probable not a GCode file. "
  8250. "Try to load it from File menu.\n "
  8251. "Attempting to create a FlatCAM CNCJob Object from "
  8252. "G-Code file failed during processing"))
  8253. return "fail"
  8254. # Register recent file
  8255. self.app.file_opened.emit("cncjob", filename)
  8256. # appGUI feedback
  8257. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  8258. def open_hpgl2(self, filename, outname=None):
  8259. """
  8260. Opens a HPGL2 file, parses it and creates a new object for
  8261. it in the program. Thread-safe.
  8262. :param outname: Name of the resulting object. None causes the name to be that of the file.
  8263. :param filename: HPGL2 file filename
  8264. :return: None
  8265. """
  8266. filename = filename
  8267. # How the object should be initialized
  8268. def obj_init(geo_obj, app_obj):
  8269. assert isinstance(geo_obj, GeometryObject), \
  8270. "Expected to initialize a GeometryObject but got %s" % type(geo_obj)
  8271. # Opening the file happens here
  8272. obj = HPGL2(self)
  8273. try:
  8274. HPGL2.parse_file(obj, filename)
  8275. except IOError:
  8276. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open file"), filename))
  8277. return "fail"
  8278. except ParseError as err:
  8279. app_obj.inform.emit('[ERROR_NOTCL] %s: %s. %s' % (_("Failed to parse file"), filename, str(err)))
  8280. app_obj.log.error(str(err))
  8281. return "fail"
  8282. except Exception as e:
  8283. app_obj.log.debug("App.open_hpgl2() --> %s" % str(e))
  8284. msg = '[ERROR] %s' % _("An internal error has occurred. See shell.\n")
  8285. msg += traceback.format_exc()
  8286. app_obj.inform.emit(msg)
  8287. return "fail"
  8288. geo_obj.multigeo = True
  8289. geo_obj.solid_geometry = deepcopy(obj.solid_geometry)
  8290. geo_obj.tools = deepcopy(obj.tools)
  8291. geo_obj.source_file = deepcopy(obj.source_file)
  8292. del obj
  8293. if not geo_obj.solid_geometry:
  8294. app_obj.inform.emit('[ERROR_NOTCL] %s' %
  8295. _("Object is not HPGL2 file or empty. Aborting object creation."))
  8296. return "fail"
  8297. self.app.log.debug("open_hpgl2()")
  8298. with self.app.proc_container.new(_("Opening HPGL2")):
  8299. # Object name
  8300. name = outname or filename.split('/')[-1].split('\\')[-1]
  8301. # # ## Object creation # ##
  8302. ret = self.app.app_obj.new_object("geometry", name, obj_init, autoselected=False)
  8303. if ret == 'fail':
  8304. self.inform.emit('[ERROR_NOTCL]%s' % _(' Open HPGL2 failed. Probable not a HPGL2 file.'))
  8305. return 'fail'
  8306. # Register recent file
  8307. self.app.file_opened.emit("geometry", filename)
  8308. # appGUI feedback
  8309. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  8310. def open_script(self, filename, outname=None, silent=False):
  8311. """
  8312. Opens a Script file, parses it and creates a new object for
  8313. it in the program. Thread-safe.
  8314. :param outname: Name of the resulting object. None causes the name to be that of the file.
  8315. :param filename: Script file filename
  8316. :param silent: If True there will be no messages printed to StatusBar
  8317. :return: None
  8318. """
  8319. def obj_init(script_obj, app_obj):
  8320. assert isinstance(script_obj, ScriptObject), \
  8321. "Expected to initialize a ScriptObject but got %s" % type(script_obj)
  8322. if silent is False:
  8323. app_obj.inform.emit('[success] %s' % _("TCL script file opened in Code Editor."))
  8324. try:
  8325. script_obj.parse_file(filename)
  8326. except IOError:
  8327. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open file"), filename))
  8328. return "fail"
  8329. except ParseError as err:
  8330. app_obj.inform.emit('[ERROR_NOTCL] %s: %s. %s' % (_("Failed to parse file"), filename, str(err)))
  8331. app_obj.log.error(str(err))
  8332. return "fail"
  8333. except Exception as e:
  8334. app_obj.log.debug("App.open_script() -> %s" % str(e))
  8335. msg = '[ERROR] %s' % _("An internal error has occurred. See shell.\n")
  8336. msg += traceback.format_exc()
  8337. app_obj.inform.emit(msg)
  8338. return "fail"
  8339. self.app.log.debug("open_script()")
  8340. with self.app.proc_container.new(_("Opening TCL Script...")):
  8341. # Object name
  8342. script_name = outname or filename.split('/')[-1].split('\\')[-1]
  8343. # Object creation
  8344. ret_val = self.app.app_obj.new_object("script", script_name, obj_init, autoselected=False, plot=False)
  8345. if ret_val == 'fail':
  8346. filename = self.defaults['global_tcl_path'] + '/' + script_name
  8347. ret_val = self.app.app_obj.new_object("script", script_name, obj_init, autoselected=False, plot=False)
  8348. if ret_val == 'fail':
  8349. self.inform.emit('[ERROR_NOTCL]%s' % _('Failed to open TCL Script.'))
  8350. return 'fail'
  8351. # Register recent file
  8352. self.app.file_opened.emit("script", filename)
  8353. # appGUI feedback
  8354. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  8355. def open_config_file(self, filename, run_from_arg=None):
  8356. """
  8357. Loads a config file from the specified file.
  8358. :param filename: Name of the file from which to load.
  8359. :param run_from_arg: if True the FlatConfig file will be open as an command line argument
  8360. :return: None
  8361. """
  8362. self.app.log.debug("Opening config file: " + filename)
  8363. if run_from_arg:
  8364. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  8365. "Canvas initialization finished in"),
  8366. '%.2f' % self.app.used_time,
  8367. _("Opening FlatCAM Config file.")),
  8368. alignment=Qt.AlignBottom | Qt.AlignLeft,
  8369. color=QtGui.QColor("gray"))
  8370. # # add the tab if it was closed
  8371. # self.ui.plot_tab_area.addTab(self.ui.text_editor_tab, _("Code Editor"))
  8372. # # first clear previous text in text editor (if any)
  8373. # self.ui.text_editor_tab.code_editor.clear()
  8374. #
  8375. # # Switch plot_area to CNCJob tab
  8376. # self.ui.plot_tab_area.setCurrentWidget(self.ui.text_editor_tab)
  8377. # close the Code editor if already open
  8378. if self.app.toggle_codeeditor:
  8379. self.app.on_toggle_code_editor()
  8380. self.app.on_toggle_code_editor()
  8381. try:
  8382. if filename:
  8383. f = QtCore.QFile(filename)
  8384. if f.open(QtCore.QIODevice.ReadOnly):
  8385. stream = QtCore.QTextStream(f)
  8386. code_edited = stream.readAll()
  8387. self.app.text_editor_tab.load_text(code_edited, clear_text=True, move_to_start=True)
  8388. f.close()
  8389. except IOError:
  8390. self.app.log.error("Failed to open config file: %s" % filename)
  8391. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open config file"), filename))
  8392. return
  8393. def open_project(self, filename, run_from_arg=None, plot=True, cli=None, from_tcl=False):
  8394. """
  8395. Loads a project from the specified file.
  8396. 1) Loads and parses file
  8397. 2) Registers the file as recently opened.
  8398. 3) Calls on_file_new()
  8399. 4) Updates options
  8400. 5) Calls app_obj.new_object() with the object's from_dict() as init method.
  8401. 6) Calls plot_all() if plot=True
  8402. :param filename: Name of the file from which to load.
  8403. :param run_from_arg: True if run for arguments
  8404. :param plot: If True plot all objects in the project
  8405. :param cli: Run from command line
  8406. :param from_tcl: True if run from Tcl Sehll
  8407. :return: None
  8408. """
  8409. self.app.log.debug("Opening project: " + filename)
  8410. # block autosaving while a project is loaded
  8411. self.app.block_autosave = True
  8412. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  8413. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  8414. if cli is None:
  8415. self.app.set_ui_title(name=_("Loading Project ... Please Wait ..."))
  8416. if run_from_arg:
  8417. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  8418. "Canvas initialization finished in"),
  8419. '%.2f' % self.app.used_time,
  8420. _("Opening FlatCAM Project file.")),
  8421. alignment=Qt.AlignBottom | Qt.AlignLeft,
  8422. color=QtGui.QColor("gray"))
  8423. # Open and parse an uncompressed Project file
  8424. try:
  8425. f = open(filename, 'r')
  8426. except IOError:
  8427. if from_tcl:
  8428. name = filename.split('/')[-1].split('\\')[-1]
  8429. filename = self.defaults['global_tcl_path'] + '/' + name
  8430. try:
  8431. f = open(filename, 'r')
  8432. except IOError:
  8433. self.app.log.error("Failed to open project file: %s" % filename)
  8434. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open project file"), filename))
  8435. return
  8436. else:
  8437. self.app.log.error("Failed to open project file: %s" % filename)
  8438. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open project file"), filename))
  8439. return
  8440. try:
  8441. d = json.load(f, object_hook=dict2obj)
  8442. except Exception as e:
  8443. self.app.log.error(
  8444. "Failed to parse project file, trying to see if it loads as an LZMA archive: %s because %s" %
  8445. (filename, str(e)))
  8446. f.close()
  8447. # Open and parse a compressed Project file
  8448. try:
  8449. with lzma.open(filename) as f:
  8450. file_content = f.read().decode('utf-8')
  8451. d = json.loads(file_content, object_hook=dict2obj)
  8452. except Exception as e:
  8453. self.app.log.error("Failed to open project file: %s with error: %s" % (filename, str(e)))
  8454. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open project file"), filename))
  8455. return
  8456. # Clear the current project
  8457. # # NOT THREAD SAFE # ##
  8458. if run_from_arg is True:
  8459. pass
  8460. elif cli is True:
  8461. self.app.delete_selection_shape()
  8462. else:
  8463. self.on_file_new()
  8464. # Project options
  8465. self.app.options.update(d['options'])
  8466. self.app.project_filename = filename
  8467. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  8468. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  8469. if cli is None:
  8470. self.app.set_screen_units(self.app.options["units"])
  8471. # Re create objects
  8472. self.app.log.debug(" **************** Started PROEJCT loading... **************** ")
  8473. for obj in d['objs']:
  8474. def obj_init(obj_inst, app_inst):
  8475. try:
  8476. obj_inst.from_dict(obj)
  8477. except Exception as e:
  8478. self.app.log('App.open_project() --> ' + str(e))
  8479. return 'fail'
  8480. self.app.log.debug("Recreating from opened project an %s object: %s" %
  8481. (obj['kind'].capitalize(), obj['options']['name']))
  8482. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  8483. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  8484. if cli is None:
  8485. self.app.set_ui_title(name="{} {}: {}".format(
  8486. _("Loading Project ... restoring"), obj['kind'].upper(), obj['options']['name']))
  8487. self.app.app_obj.new_object(obj['kind'], obj['options']['name'], obj_init, plot=plot)
  8488. self.inform.emit('[success] %s: %s' % (_("Project loaded from"), filename))
  8489. self.app.should_we_save = False
  8490. self.app.file_opened.emit("project", filename)
  8491. # restore autosaving after a project was loaded
  8492. self.app.block_autosave = False
  8493. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  8494. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  8495. if cli is None:
  8496. self.app.set_ui_title(name=self.app.project_filename)
  8497. self.app.log.debug(" **************** Finished PROJECT loading... **************** ")
  8498. def save_project(self, filename, quit_action=False, silent=False, from_tcl=False):
  8499. """
  8500. Saves the current project to the specified file.
  8501. :param filename: Name of the file in which to save.
  8502. :type filename: str
  8503. :param quit_action: if the project saving will be followed by an app quit; boolean
  8504. :param silent: if True will not display status messages
  8505. :param from_tcl True is run from Tcl Shell
  8506. :return: None
  8507. """
  8508. self.app.log.debug("save_project()")
  8509. self.app.save_in_progress = True
  8510. with self.app.proc_container.new(_("Saving FlatCAM Project")):
  8511. # Capture the latest changes
  8512. # Current object
  8513. try:
  8514. current_object = self.app.collection.get_active()
  8515. if current_object:
  8516. current_object.read_form()
  8517. except Exception as e:
  8518. self.app.log.debug("save_project() --> There was no active object. Skipping read_form. %s" % str(e))
  8519. # Serialize the whole project
  8520. d = {
  8521. "objs": [obj.to_dict() for obj in self.app.collection.get_list()],
  8522. "options": self.options,
  8523. "version": self.version
  8524. }
  8525. if self.defaults["global_save_compressed"] is True:
  8526. with lzma.open(filename, "w", preset=int(self.defaults['global_compression_level'])) as f:
  8527. g = json.dumps(d, default=to_dict, indent=2, sort_keys=True).encode('utf-8')
  8528. # # Write
  8529. f.write(g)
  8530. self.inform.emit('[success] %s: %s' % (_("Project saved to"), filename))
  8531. else:
  8532. # Open file
  8533. try:
  8534. f = open(filename, 'w')
  8535. except IOError:
  8536. self.app.log.error("Failed to open file for saving: %s", filename)
  8537. self.inform.emit('[ERROR_NOTCL] %s' % _("The object is used by another application."))
  8538. return
  8539. # Write
  8540. json.dump(d, f, default=to_dict, indent=2, sort_keys=True)
  8541. f.close()
  8542. # verification of the saved project
  8543. # Open and parse
  8544. try:
  8545. saved_f = open(filename, 'r')
  8546. except IOError:
  8547. if silent is False:
  8548. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  8549. (_("Failed to verify project file"), filename, _("Retry to save it.")))
  8550. return
  8551. try:
  8552. saved_d = json.load(saved_f, object_hook=dict2obj)
  8553. except Exception:
  8554. if silent is False:
  8555. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  8556. (_("Failed to parse saved project file"), filename, _("Retry to save it.")))
  8557. f.close()
  8558. return
  8559. saved_f.close()
  8560. if silent is False:
  8561. if 'version' in saved_d:
  8562. self.inform.emit('[success] %s: %s' % (_("Project saved to"), filename))
  8563. else:
  8564. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  8565. (_("Failed to parse saved project file"), filename, _("Retry to save it.")))
  8566. tb_settings = QSettings("Open Source", "FlatCAM")
  8567. lock_state = self.app.ui.lock_action.isChecked()
  8568. tb_settings.setValue('toolbar_lock', lock_state)
  8569. # This will write the setting to the platform specific storage.
  8570. del tb_settings
  8571. # if quit:
  8572. # t = threading.Thread(target=lambda: self.check_project_file_size(1, filename=filename))
  8573. # t.start()
  8574. self.app.start_delayed_quit(delay=500, filename=filename, should_quit=quit_action)
  8575. def save_source_file(self, obj_name, filename, use_thread=True):
  8576. """
  8577. Exports a FlatCAM Object to an Gerber/Excellon file.
  8578. :param obj_name: the name of the FlatCAM object for which to save it's embedded source file
  8579. :param filename: Path to the Gerber file to save to.
  8580. :param use_thread: if to be run in a separate thread
  8581. :return:
  8582. """
  8583. if filename is None:
  8584. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  8585. is not None else self.defaults["global_last_folder"]
  8586. self.app.log.debug("save source file()")
  8587. obj = self.app.collection.get_by_name(obj_name)
  8588. file_string = StringIO(obj.source_file)
  8589. time_string = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  8590. if file_string.getvalue() == '':
  8591. self.inform.emit('[ERROR_NOTCL] %s' %
  8592. _("Save cancelled because source file is empty. Try to export the file."))
  8593. return 'fail'
  8594. try:
  8595. with open(filename, 'w') as file:
  8596. file.writelines('G04*\n')
  8597. file.writelines('G04 %s (RE)GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s*\n' %
  8598. (obj.kind.upper(), str(self.app.version), str(self.app.version_date)))
  8599. file.writelines('G04 Filename: %s*\n' % str(obj_name))
  8600. file.writelines('G04 Created on : %s*\n' % time_string)
  8601. for line in file_string:
  8602. file.writelines(line)
  8603. except PermissionError:
  8604. self.inform.emit('[WARNING] %s' %
  8605. _("Permission denied, saving not possible.\n"
  8606. "Most likely another app is holding the file open and not accessible."))
  8607. return 'fail'
  8608. def on_file_savedefaults(self):
  8609. """
  8610. Callback for menu item File->Save Defaults. Saves application default options
  8611. ``self.defaults`` to current_defaults.FlatConfig.
  8612. :return: None
  8613. """
  8614. self.app.preferencesUiManager.save_defaults()
  8615. # end of file