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. show_splash = 0
  400. # ###########################################################################################################
  401. # ######################################### Initialize GUI ##################################################
  402. # ###########################################################################################################
  403. # FlatCAM colors used in plotting
  404. self.FC_light_green = '#BBF268BF'
  405. self.FC_dark_green = '#006E20BF'
  406. self.FC_light_blue = '#a5a5ffbf'
  407. self.FC_dark_blue = '#0000ffbf'
  408. theme_settings = QtCore.QSettings("Open Source", "FlatCAM")
  409. if theme_settings.contains("theme"):
  410. theme = theme_settings.value('theme', type=str)
  411. else:
  412. theme = 'white'
  413. if self.defaults["global_cursor_color_enabled"]:
  414. self.cursor_color_3D = self.defaults["global_cursor_color"]
  415. else:
  416. if theme == 'white':
  417. self.cursor_color_3D = 'black'
  418. else:
  419. self.cursor_color_3D = 'gray'
  420. # update the defaults dict with the setting in QSetting
  421. self.defaults['global_theme'] = theme
  422. self.ui = MainGUI(self)
  423. # set FlatCAM units in the Status bar
  424. self.set_screen_units(self.defaults['units'])
  425. # ###########################################################################################################
  426. # ########################################### AUTOSAVE SETUP ################################################
  427. # ###########################################################################################################
  428. self.block_autosave = False
  429. self.autosave_timer = QtCore.QTimer(self)
  430. self.save_project_auto_update()
  431. self.autosave_timer.timeout.connect(self.save_project_auto)
  432. # ###########################################################################################################
  433. # #################################### LOAD PREPROCESSORS ###################################################
  434. # ###########################################################################################################
  435. # ----------------------------------------- WARNING --------------------------------------------------------
  436. # Preprocessors need to be loaded before the Preferences Manager builds the Preferences
  437. # That's because the number of preprocessors can vary and here the comboboxes are populated
  438. # -----------------------------------------------------------------------------------------------------------
  439. # a dictionary that have as keys the name of the preprocessor files and the value is the class from
  440. # the preprocessor file
  441. self.preprocessors = load_preprocessors(self)
  442. # make sure that always the 'default' preprocessor is the first item in the dictionary
  443. if 'default' in self.preprocessors.keys():
  444. new_ppp_dict = {}
  445. # add the 'default' name first in the dict after removing from the preprocessor's dictionary
  446. default_pp = self.preprocessors.pop('default')
  447. new_ppp_dict['default'] = default_pp
  448. # then add the rest of the keys
  449. for name, val_class in self.preprocessors.items():
  450. new_ppp_dict[name] = val_class
  451. # and now put back the ordered dict with 'default' key first
  452. self.preprocessors = new_ppp_dict
  453. # populate the Preprocessor ComboBoxes in the PREFERENCES
  454. for name in list(self.preprocessors.keys()):
  455. # 'Paste' preprocessors are to be used only in the Solder Paste Dispensing Tool
  456. if name.partition('_')[0] == 'Paste':
  457. self.ui.tools_defaults_form.tools_solderpaste_group.pp_combo.addItem(name)
  458. continue
  459. self.ui.geometry_defaults_form.geometry_opt_group.pp_geometry_name_cb.addItem(name)
  460. # HPGL preprocessor is only for Geometry objects therefore it should not be in the Excellon Preferences
  461. if name == 'hpgl':
  462. continue
  463. self.ui.tools_defaults_form.tools_drill_group.pp_excellon_name_cb.addItem(name)
  464. # add ToolTips for the Preprocessor ComboBoxes in Preferences
  465. for it in range(self.ui.tools_defaults_form.tools_solderpaste_group.pp_combo.count()):
  466. self.ui.tools_defaults_form.tools_solderpaste_group.pp_combo.setItemData(
  467. it, self.ui.tools_defaults_form.tools_solderpaste_group.pp_combo.itemText(it), QtCore.Qt.ToolTipRole)
  468. for it in range(self.ui.geometry_defaults_form.geometry_opt_group.pp_geometry_name_cb.count()):
  469. self.ui.geometry_defaults_form.geometry_opt_group.pp_geometry_name_cb.setItemData(
  470. it, self.ui.geometry_defaults_form.geometry_opt_group.pp_geometry_name_cb.itemText(it),
  471. QtCore.Qt.ToolTipRole)
  472. for it in range(self.ui.tools_defaults_form.tools_drill_group.pp_excellon_name_cb.count()):
  473. self.ui.tools_defaults_form.tools_drill_group.pp_excellon_name_cb.setItemData(
  474. it, self.ui.tools_defaults_form.tools_drill_group.pp_excellon_name_cb.itemText(it),
  475. QtCore.Qt.ToolTipRole)
  476. # ###########################################################################################################
  477. # ##################################### UPDATE PREFERENCES GUI FORMS ########################################
  478. # ###########################################################################################################
  479. self.preferencesUiManager = PreferencesUIManager(defaults=self.defaults, data_path=self.data_path, ui=self.ui,
  480. inform=self.inform)
  481. self.preferencesUiManager.defaults_write_form()
  482. # When the self.defaults dictionary changes will update the Preferences GUI forms
  483. self.defaults.set_change_callback(self.on_defaults_dict_change)
  484. # ###########################################################################################################
  485. # ##################################### FIRST RUN SECTION ###################################################
  486. # ################################ It's done only once after install #####################################
  487. # ###########################################################################################################
  488. if self.defaults["first_run"] is True:
  489. # ONLY AT FIRST STARTUP INIT THE GUI LAYOUT TO 'minimal'
  490. initial_lay = 'minimal'
  491. self.ui.general_defaults_form.general_gui_group.on_layout(lay=initial_lay)
  492. # Set the combobox in Preferences to the current layout
  493. idx = self.ui.general_defaults_form.general_gui_group.layout_combo.findText(initial_lay)
  494. self.ui.general_defaults_form.general_gui_group.layout_combo.setCurrentIndex(idx)
  495. # after the first run, this object should be False
  496. self.defaults["first_run"] = False
  497. self.preferencesUiManager.save_defaults(silent=True)
  498. # ###########################################################################################################
  499. # ############################################ Data #########################################################
  500. # ###########################################################################################################
  501. self.recent = []
  502. self.recent_projects = []
  503. self.clipboard = QtWidgets.QApplication.clipboard()
  504. self.project_filename = None
  505. self.toggle_units_ignore = False
  506. self.main_thread = QtWidgets.QApplication.instance().thread()
  507. # ###########################################################################################################
  508. # ########################################## LOAD LANGUAGES ################################################
  509. # ###########################################################################################################
  510. self.languages = fcTranslate.load_languages()
  511. for name in sorted(self.languages.values()):
  512. self.ui.general_defaults_form.general_app_group.language_cb.addItem(name)
  513. # ###########################################################################################################
  514. # ####################################### APPLY APP LANGUAGE ################################################
  515. # ###########################################################################################################
  516. ret_val = fcTranslate.apply_language('strings')
  517. if ret_val == "no language":
  518. self.inform.emit('[ERROR] %s' % _("Could not find the Language files. The App strings are missing."))
  519. log.debug("Could not find the Language files. The App strings are missing.")
  520. else:
  521. # make the current language the current selection on the language combobox
  522. self.ui.general_defaults_form.general_app_group.language_cb.setCurrentText(ret_val)
  523. log.debug("App.__init__() --> Applied %s language." % str(ret_val).capitalize())
  524. # ###########################################################################################################
  525. # ###################################### CREATE UNIQUE SERIAL NUMBER ########################################
  526. # ###########################################################################################################
  527. chars = 'abcdefghijklmnopqrstuvwxyz0123456789'
  528. if self.defaults['global_serial'] == 0 or len(str(self.defaults['global_serial'])) < 10:
  529. self.defaults['global_serial'] = ''.join([random.choice(chars) for __ in range(20)])
  530. self.preferencesUiManager.save_defaults(silent=True, first_time=True)
  531. self.defaults.propagate_defaults()
  532. # ###########################################################################################################
  533. # ######################################## UPDATE THE OPTIONS ###############################################
  534. # ###########################################################################################################
  535. self.options = LoudDict()
  536. # -----------------------------------------------------------------------------------------------------------
  537. # Update the self.options from the self.defaults
  538. # The self.defaults holds the application defaults while the self.options holds the object defaults
  539. # -----------------------------------------------------------------------------------------------------------
  540. # Copy app defaults to project options
  541. for def_key, def_val in self.defaults.items():
  542. self.options[def_key] = deepcopy(def_val)
  543. self.preferencesUiManager.show_preferences_gui()
  544. # ### End of Data ####
  545. # ###########################################################################################################
  546. # #################################### SETUP OBJECT COLLECTION ##############################################
  547. # ###########################################################################################################
  548. self.collection = ObjectCollection(app=self)
  549. self.ui.project_tab_layout.addWidget(self.collection.view)
  550. self.app_obj = AppObject(app=self)
  551. # ### Adjust tabs width ## ##
  552. # self.collection.view.setMinimumWidth(self.ui.options_scroll_area.widget().sizeHint().width() +
  553. # self.ui.options_scroll_area.verticalScrollBar().sizeHint().width())
  554. self.collection.view.setMinimumWidth(290)
  555. self.log.debug("Finished creating Object Collection.")
  556. # ###########################################################################################################
  557. # ######################################## SETUP Plot Area ##################################################
  558. # ###########################################################################################################
  559. # determine if the Legacy Graphic Engine is to be used or the OpenGL one
  560. if self.defaults["global_graphic_engine"] == '3D':
  561. self.is_legacy = False
  562. else:
  563. self.is_legacy = True
  564. # Event signals disconnect id holders
  565. self.mp = None
  566. self.mm = None
  567. self.mr = None
  568. self.mdc = None
  569. self.mp_zc = None
  570. self.kp = None
  571. # Matplotlib axis
  572. self.axes = None
  573. if show_splash:
  574. self.splash.showMessage(_("FlatCAM is initializing ...\n"
  575. "Canvas initialization started."),
  576. alignment=Qt.AlignBottom | Qt.AlignLeft,
  577. color=QtGui.QColor("gray"))
  578. start_plot_time = time.time() # debug
  579. self.plotcanvas = None
  580. self.app_cursor = None
  581. self.hover_shapes = None
  582. self.log.debug("Setting up canvas: %s" % str(self.defaults["global_graphic_engine"]))
  583. # setup the PlotCanvas
  584. self.on_plotcanvas_setup()
  585. end_plot_time = time.time()
  586. self.used_time = end_plot_time - start_plot_time
  587. self.log.debug("Finished Canvas initialization in %s seconds." % str(self.used_time))
  588. if show_splash:
  589. self.splash.showMessage('%s: %ssec' % (_("FlatCAM is initializing ...\n"
  590. "Canvas initialization started.\n"
  591. "Canvas initialization finished in"), '%.2f' % self.used_time),
  592. alignment=Qt.AlignBottom | Qt.AlignLeft,
  593. color=QtGui.QColor("gray"))
  594. self.ui.splitter.setStretchFactor(1, 2)
  595. # ###########################################################################################################
  596. # ############################################### SYS TRAY ##################################################
  597. # ###########################################################################################################
  598. if self.defaults["global_systray_icon"]:
  599. self.parent_w = QtWidgets.QWidget()
  600. if self.cmd_line_headless == 1:
  601. self.trayIcon = FlatCAMSystemTray(app=self,
  602. icon=QtGui.QIcon(self.resource_location +
  603. '/flatcam_icon32_green.png'),
  604. headless=True,
  605. parent=self.parent_w)
  606. else:
  607. self.trayIcon = FlatCAMSystemTray(app=self,
  608. icon=QtGui.QIcon(self.resource_location +
  609. '/flatcam_icon32_green.png'),
  610. parent=self.parent_w)
  611. # ###########################################################################################################
  612. # ############################################### Worker SETUP ##############################################
  613. # ###########################################################################################################
  614. if self.defaults["global_worker_number"]:
  615. self.workers = WorkerStack(workers_number=int(self.defaults["global_worker_number"]))
  616. else:
  617. self.workers = WorkerStack(workers_number=2)
  618. self.worker_task.connect(self.workers.add_task)
  619. self.log.debug("Finished creating Workers crew.")
  620. # ###########################################################################################################
  621. # ############################################# Activity Monitor ############################################
  622. # ###########################################################################################################
  623. # self.activity_view = FlatCAMActivityView(app=self)
  624. # self.ui.infobar.addWidget(self.activity_view)
  625. self.proc_container = FCVisibleProcessContainer(self.ui.activity_view)
  626. # ###########################################################################################################
  627. # ########################################## Other setups ###################################################
  628. # ###########################################################################################################
  629. # to use for tools like Distance tool who depends on the event sources who are changed inside the appEditors
  630. # depending on from where those tools are called different actions can be done
  631. self.call_source = 'app'
  632. # this is a flag to signal to other tools that the ui tooltab is locked and not accessible
  633. self.tool_tab_locked = False
  634. # decide if to show or hide the Notebook side of the screen at startup
  635. if self.defaults["global_project_at_startup"] is True:
  636. self.ui.splitter.setSizes([1, 1])
  637. else:
  638. self.ui.splitter.setSizes([0, 1])
  639. # Sets up FlatCAMObj, FCProcess and FCProcessContainer.
  640. self.setup_default_properties_tab()
  641. # ###########################################################################################################
  642. # ####################################### Auto-complete KEYWORDS ############################################
  643. # ###########################################################################################################
  644. self.tcl_commands_list = ['add_circle', 'add_poly', 'add_polygon', 'add_polyline', 'add_rectangle',
  645. 'aligndrill', 'aligndrillgrid', 'bbox', 'clear', 'cncjob', 'cutout',
  646. 'del', 'drillcncjob', 'export_dxf', 'edxf', 'export_excellon',
  647. 'export_exc',
  648. 'export_gcode', 'export_gerber', 'export_svg', 'ext', 'exteriors', 'follow',
  649. 'geo_union', 'geocutout', 'get_bounds', 'get_names', 'get_path', 'get_sys', 'help',
  650. 'interiors', 'isolate', 'join_excellon',
  651. 'join_geometry', 'list_sys', 'milld', 'mills', 'milldrills', 'millslots',
  652. 'mirror', 'ncc',
  653. 'ncr', 'new', 'new_geometry', 'non_copper_regions', 'offset',
  654. 'open_dxf', 'open_excellon', 'open_gcode', 'open_gerber', 'open_project', 'open_svg',
  655. 'options', 'origin',
  656. 'paint', 'panelize', 'plot_all', 'plot_objects', 'plot_status', 'quit_flatcam',
  657. 'save', 'save_project',
  658. 'save_sys', 'scale', 'set_active', 'set_origin', 'set_path', 'set_sys',
  659. 'skew', 'subtract_poly', 'subtract_rectangle',
  660. 'version', 'write_gcode'
  661. ]
  662. self.default_keywords = ['Desktop', 'Documents', 'FlatConfig', 'FlatPrj', 'False', 'Marius', 'My Documents',
  663. 'Paste_1',
  664. 'Repetier', 'Roland_MDX_20', 'Users', 'Toolchange_Custom', 'Toolchange_Probe_MACH3',
  665. 'Toolchange_manual', 'True', 'Users',
  666. 'all', 'auto', 'axis',
  667. 'axisoffset', 'box', 'center_x', 'center_y', 'columns', 'combine', 'connect',
  668. 'contour', 'default',
  669. 'depthperpass', 'dia', 'diatol', 'dist', 'drilled_dias', 'drillz', 'dpp',
  670. 'dwelltime', 'extracut_length', 'endxy', 'enz', 'f', 'feedrate',
  671. 'feedrate_z', 'grbl_11', 'GRBL_laser', 'gridoffsety', 'gridx', 'gridy',
  672. 'has_offset', 'holes', 'hpgl', 'iso_type', 'line_xyz', 'margin', 'marlin', 'method',
  673. 'milled_dias', 'minoffset', 'name', 'offset', 'opt_type', 'order',
  674. 'outname', 'overlap', 'passes', 'postamble', 'pp', 'ppname_e', 'ppname_g',
  675. 'preamble', 'radius', 'ref', 'rest', 'rows', 'shellvar_', 'scale_factor',
  676. 'spacing_columns',
  677. 'spacing_rows', 'spindlespeed', 'startz', 'startxy',
  678. 'toolchange_xy', 'toolchangez', 'travelz',
  679. 'tooldia', 'use_threads', 'value',
  680. 'x', 'x0', 'x1', 'y', 'y0', 'y1', 'z_cut', 'z_move'
  681. ]
  682. self.tcl_keywords = [
  683. 'after', 'append', 'apply', 'argc', 'argv', 'argv0', 'array', 'attemptckalloc', 'attemptckrealloc',
  684. 'auto_execok', 'auto_import', 'auto_load', 'auto_mkindex', 'auto_path', 'auto_qualify', 'auto_reset',
  685. 'bgerror', 'binary', 'break', 'case', 'catch', 'cd', 'chan', 'ckalloc', 'ckfree', 'ckrealloc', 'clock',
  686. 'close', 'concat', 'continue', 'coroutine', 'dde', 'dict', 'encoding', 'env', 'eof', 'error', 'errorCode',
  687. 'errorInfo', 'eval', 'exec', 'exit', 'expr', 'fblocked', 'fconfigure', 'fcopy', 'file', 'fileevent',
  688. 'filename', 'flush', 'for', 'foreach', 'format', 'gets', 'glob', 'global', 'history', 'http', 'if', 'incr',
  689. 'info', 'interp', 'join', 'lappend', 'lassign', 'lindex', 'linsert', 'list', 'llength', 'load', 'lrange',
  690. 'lrepeat', 'lreplace', 'lreverse', 'lsearch', 'lset', 'lsort', 'mathfunc', 'mathop', 'memory', 'msgcat',
  691. 'my', 'namespace', 'next', 'nextto', 'open', 'package', 'parray', 'pid', 'pkg_mkIndex', 'platform',
  692. 'proc', 'puts', 'pwd', 're_syntax', 'read', 'refchan', 'regexp', 'registry', 'regsub', 'rename', 'return',
  693. 'safe', 'scan', 'seek', 'self', 'set', 'socket', 'source', 'split', 'string', 'subst', 'switch',
  694. 'tailcall', 'Tcl', 'Tcl_Access', 'Tcl_AddErrorInfo', 'Tcl_AddObjErrorInfo', 'Tcl_AlertNotifier',
  695. 'Tcl_Alloc', 'Tcl_AllocHashEntryProc', 'Tcl_AllocStatBuf', 'Tcl_AllowExceptions', 'Tcl_AppendAllObjTypes',
  696. 'Tcl_AppendElement', 'Tcl_AppendExportList', 'Tcl_AppendFormatToObj', 'Tcl_AppendLimitedToObj',
  697. 'Tcl_AppendObjToErrorInfo', 'Tcl_AppendObjToObj', 'Tcl_AppendPrintfToObj', 'Tcl_AppendResult',
  698. 'Tcl_AppendResultVA', 'Tcl_AppendStringsToObj', 'Tcl_AppendStringsToObjVA', 'Tcl_AppendToObj',
  699. 'Tcl_AppendUnicodeToObj', 'Tcl_AppInit', 'Tcl_AppInitProc', 'Tcl_ArgvInfo', 'Tcl_AsyncCreate',
  700. 'Tcl_AsyncDelete', 'Tcl_AsyncInvoke', 'Tcl_AsyncMark', 'Tcl_AsyncProc', 'Tcl_AsyncReady',
  701. 'Tcl_AttemptAlloc', 'Tcl_AttemptRealloc', 'Tcl_AttemptSetObjLength', 'Tcl_BackgroundError',
  702. 'Tcl_BackgroundException', 'Tcl_Backslash', 'Tcl_BadChannelOption', 'Tcl_CallWhenDeleted', 'Tcl_Canceled',
  703. 'Tcl_CancelEval', 'Tcl_CancelIdleCall', 'Tcl_ChannelBlockModeProc', 'Tcl_ChannelBuffered',
  704. 'Tcl_ChannelClose2Proc', 'Tcl_ChannelCloseProc', 'Tcl_ChannelFlushProc', 'Tcl_ChannelGetHandleProc',
  705. 'Tcl_ChannelGetOptionProc', 'Tcl_ChannelHandlerProc', 'Tcl_ChannelInputProc', 'Tcl_ChannelName',
  706. 'Tcl_ChannelOutputProc', 'Tcl_ChannelProc', 'Tcl_ChannelSeekProc', 'Tcl_ChannelSetOptionProc',
  707. 'Tcl_ChannelThreadActionProc', 'Tcl_ChannelTruncateProc', 'Tcl_ChannelType', 'Tcl_ChannelVersion',
  708. 'Tcl_ChannelWatchProc', 'Tcl_ChannelWideSeekProc', 'Tcl_Chdir', 'Tcl_ClassGetMetadata',
  709. 'Tcl_ClassSetConstructor', 'Tcl_ClassSetDestructor', 'Tcl_ClassSetMetadata', 'Tcl_ClearChannelHandlers',
  710. 'Tcl_CloneProc', 'Tcl_Close', 'Tcl_CloseProc', 'Tcl_CmdDeleteProc', 'Tcl_CmdInfo',
  711. 'Tcl_CmdObjTraceDeleteProc', 'Tcl_CmdObjTraceProc', 'Tcl_CmdProc', 'Tcl_CmdTraceProc',
  712. 'Tcl_CommandComplete', 'Tcl_CommandTraceInfo', 'Tcl_CommandTraceProc', 'Tcl_CompareHashKeysProc',
  713. 'Tcl_Concat', 'Tcl_ConcatObj', 'Tcl_ConditionFinalize', 'Tcl_ConditionNotify', 'Tcl_ConditionWait',
  714. 'Tcl_Config', 'Tcl_ConvertCountedElement', 'Tcl_ConvertElement', 'Tcl_ConvertToType',
  715. 'Tcl_CopyObjectInstance', 'Tcl_CreateAlias', 'Tcl_CreateAliasObj', 'Tcl_CreateChannel',
  716. 'Tcl_CreateChannelHandler', 'Tcl_CreateCloseHandler', 'Tcl_CreateCommand', 'Tcl_CreateEncoding',
  717. 'Tcl_CreateEnsemble', 'Tcl_CreateEventSource', 'Tcl_CreateExitHandler', 'Tcl_CreateFileHandler',
  718. 'Tcl_CreateHashEntry', 'Tcl_CreateInterp', 'Tcl_CreateMathFunc', 'Tcl_CreateNamespace',
  719. 'Tcl_CreateObjCommand', 'Tcl_CreateObjTrace', 'Tcl_CreateSlave', 'Tcl_CreateThread',
  720. 'Tcl_CreateThreadExitHandler', 'Tcl_CreateTimerHandler', 'Tcl_CreateTrace',
  721. 'Tcl_CutChannel', 'Tcl_DecrRefCount', 'Tcl_DeleteAssocData', 'Tcl_DeleteChannelHandler',
  722. 'Tcl_DeleteCloseHandler', 'Tcl_DeleteCommand', 'Tcl_DeleteCommandFromToken', 'Tcl_DeleteEvents',
  723. 'Tcl_DeleteEventSource', 'Tcl_DeleteExitHandler', 'Tcl_DeleteFileHandler', 'Tcl_DeleteHashEntry',
  724. 'Tcl_DeleteHashTable', 'Tcl_DeleteInterp', 'Tcl_DeleteNamespace', 'Tcl_DeleteThreadExitHandler',
  725. 'Tcl_DeleteTimerHandler', 'Tcl_DeleteTrace', 'Tcl_DetachChannel', 'Tcl_DetachPids', 'Tcl_DictObjDone',
  726. 'Tcl_DictObjFirst', 'Tcl_DictObjGet', 'Tcl_DictObjNext', 'Tcl_DictObjPut', 'Tcl_DictObjPutKeyList',
  727. 'Tcl_DictObjRemove', 'Tcl_DictObjRemoveKeyList', 'Tcl_DictObjSize', 'Tcl_DiscardInterpState',
  728. 'Tcl_DiscardResult', 'Tcl_DontCallWhenDeleted', 'Tcl_DoOneEvent', 'Tcl_DoWhenIdle',
  729. 'Tcl_DriverBlockModeProc', 'Tcl_DriverClose2Proc', 'Tcl_DriverCloseProc', 'Tcl_DriverFlushProc',
  730. 'Tcl_DriverGetHandleProc', 'Tcl_DriverGetOptionProc', 'Tcl_DriverHandlerProc', 'Tcl_DriverInputProc',
  731. 'Tcl_DriverOutputProc', 'Tcl_DriverSeekProc', 'Tcl_DriverSetOptionProc', 'Tcl_DriverThreadActionProc',
  732. 'Tcl_DriverTruncateProc', 'Tcl_DriverWatchProc', 'Tcl_DriverWideSeekProc', 'Tcl_DStringAppend',
  733. 'Tcl_DStringAppendElement', 'Tcl_DStringEndSublist', 'Tcl_DStringFree', 'Tcl_DStringGetResult',
  734. 'Tcl_DStringInit', 'Tcl_DStringLength', 'Tcl_DStringResult', 'Tcl_DStringSetLength',
  735. 'Tcl_DStringStartSublist', 'Tcl_DStringTrunc', 'Tcl_DStringValue', 'Tcl_DumpActiveMemory',
  736. 'Tcl_DupInternalRepProc', 'Tcl_DuplicateObj', 'Tcl_EncodingConvertProc', 'Tcl_EncodingFreeProc',
  737. 'Tcl_EncodingType', 'tcl_endOfWord', 'Tcl_Eof', 'Tcl_ErrnoId', 'Tcl_ErrnoMsg', 'Tcl_Eval', 'Tcl_EvalEx',
  738. 'Tcl_EvalFile', 'Tcl_EvalObjEx', 'Tcl_EvalObjv', 'Tcl_EvalTokens', 'Tcl_EvalTokensStandard', 'Tcl_Event',
  739. 'Tcl_EventCheckProc', 'Tcl_EventDeleteProc', 'Tcl_EventProc', 'Tcl_EventSetupProc', 'Tcl_EventuallyFree',
  740. 'Tcl_Exit', 'Tcl_ExitProc', 'Tcl_ExitThread', 'Tcl_Export', 'Tcl_ExposeCommand', 'Tcl_ExprBoolean',
  741. 'Tcl_ExprBooleanObj', 'Tcl_ExprDouble', 'Tcl_ExprDoubleObj', 'Tcl_ExprLong', 'Tcl_ExprLongObj',
  742. 'Tcl_ExprObj', 'Tcl_ExprString', 'Tcl_ExternalToUtf', 'Tcl_ExternalToUtfDString', 'Tcl_FileProc',
  743. 'Tcl_Filesystem', 'Tcl_Finalize', 'Tcl_FinalizeNotifier', 'Tcl_FinalizeThread', 'Tcl_FindCommand',
  744. 'Tcl_FindEnsemble', 'Tcl_FindExecutable', 'Tcl_FindHashEntry', 'tcl_findLibrary', 'Tcl_FindNamespace',
  745. 'Tcl_FirstHashEntry', 'Tcl_Flush', 'Tcl_ForgetImport', 'Tcl_Format', 'Tcl_FreeHashEntryProc',
  746. 'Tcl_FreeInternalRepProc', 'Tcl_FreeParse', 'Tcl_FreeProc', 'Tcl_FreeResult',
  747. 'Tcl_Free·\xa0Tcl_FreeEncoding', 'Tcl_FSAccess', 'Tcl_FSAccessProc', 'Tcl_FSChdir',
  748. 'Tcl_FSChdirProc', 'Tcl_FSConvertToPathType', 'Tcl_FSCopyDirectory', 'Tcl_FSCopyDirectoryProc',
  749. 'Tcl_FSCopyFile', 'Tcl_FSCopyFileProc', 'Tcl_FSCreateDirectory', 'Tcl_FSCreateDirectoryProc',
  750. 'Tcl_FSCreateInternalRepProc', 'Tcl_FSData', 'Tcl_FSDeleteFile', 'Tcl_FSDeleteFileProc',
  751. 'Tcl_FSDupInternalRepProc', 'Tcl_FSEqualPaths', 'Tcl_FSEvalFile', 'Tcl_FSEvalFileEx',
  752. 'Tcl_FSFileAttrsGet', 'Tcl_FSFileAttrsGetProc', 'Tcl_FSFileAttrsSet', 'Tcl_FSFileAttrsSetProc',
  753. 'Tcl_FSFileAttrStrings', 'Tcl_FSFileSystemInfo', 'Tcl_FSFilesystemPathTypeProc',
  754. 'Tcl_FSFilesystemSeparatorProc', 'Tcl_FSFreeInternalRepProc', 'Tcl_FSGetCwd', 'Tcl_FSGetCwdProc',
  755. 'Tcl_FSGetFileSystemForPath', 'Tcl_FSGetInternalRep', 'Tcl_FSGetNativePath', 'Tcl_FSGetNormalizedPath',
  756. 'Tcl_FSGetPathType', 'Tcl_FSGetTranslatedPath', 'Tcl_FSGetTranslatedStringPath',
  757. 'Tcl_FSInternalToNormalizedProc', 'Tcl_FSJoinPath', 'Tcl_FSJoinToPath', 'Tcl_FSLinkProc',
  758. 'Tcl_FSLink·\xa0Tcl_FSListVolumes', 'Tcl_FSListVolumesProc', 'Tcl_FSLoadFile', 'Tcl_FSLoadFileProc',
  759. 'Tcl_FSLstat', 'Tcl_FSLstatProc', 'Tcl_FSMatchInDirectory', 'Tcl_FSMatchInDirectoryProc',
  760. 'Tcl_FSMountsChanged', 'Tcl_FSNewNativePath', 'Tcl_FSNormalizePathProc', 'Tcl_FSOpenFileChannel',
  761. 'Tcl_FSOpenFileChannelProc', 'Tcl_FSPathInFilesystemProc', 'Tcl_FSPathSeparator', 'Tcl_FSRegister',
  762. 'Tcl_FSRemoveDirectory', 'Tcl_FSRemoveDirectoryProc', 'Tcl_FSRenameFile', 'Tcl_FSRenameFileProc',
  763. 'Tcl_FSSplitPath', 'Tcl_FSStat', 'Tcl_FSStatProc', 'Tcl_FSUnloadFile', 'Tcl_FSUnloadFileProc',
  764. 'Tcl_FSUnregister', 'Tcl_FSUtime', 'Tcl_FSUtimeProc', 'Tcl_GetAccessTimeFromStat', 'Tcl_GetAlias',
  765. 'Tcl_GetAliasObj', 'Tcl_GetAssocData', 'Tcl_GetBignumFromObj', 'Tcl_GetBlocksFromStat',
  766. 'Tcl_GetBlockSizeFromStat', 'Tcl_GetBoolean', 'Tcl_GetBooleanFromObj', 'Tcl_GetByteArrayFromObj',
  767. 'Tcl_GetChangeTimeFromStat', 'Tcl_GetChannel', 'Tcl_GetChannelBufferSize', 'Tcl_GetChannelError',
  768. 'Tcl_GetChannelErrorInterp', 'Tcl_GetChannelHandle', 'Tcl_GetChannelInstanceData', 'Tcl_GetChannelMode',
  769. 'Tcl_GetChannelName', 'Tcl_GetChannelNames', 'Tcl_GetChannelNamesEx', 'Tcl_GetChannelOption',
  770. 'Tcl_GetChannelThread', 'Tcl_GetChannelType', 'Tcl_GetCharLength', 'Tcl_GetClassAsObject',
  771. 'Tcl_GetCommandFromObj', 'Tcl_GetCommandFullName', 'Tcl_GetCommandInfo', 'Tcl_GetCommandInfoFromToken',
  772. 'Tcl_GetCommandName', 'Tcl_GetCurrentNamespace', 'Tcl_GetCurrentThread', 'Tcl_GetCwd',
  773. 'Tcl_GetDefaultEncodingDir', 'Tcl_GetDeviceTypeFromStat', 'Tcl_GetDouble', 'Tcl_GetDoubleFromObj',
  774. 'Tcl_GetEncoding', 'Tcl_GetEncodingFromObj', 'Tcl_GetEncodingName', 'Tcl_GetEncodingNameFromEnvironment',
  775. 'Tcl_GetEncodingNames', 'Tcl_GetEncodingSearchPath', 'Tcl_GetEnsembleFlags', 'Tcl_GetEnsembleMappingDict',
  776. 'Tcl_GetEnsembleNamespace', 'Tcl_GetEnsembleParameterList', 'Tcl_GetEnsembleSubcommandList',
  777. 'Tcl_GetEnsembleUnknownHandler', 'Tcl_GetErrno', 'Tcl_GetErrorLine', 'Tcl_GetFSDeviceFromStat',
  778. 'Tcl_GetFSInodeFromStat', 'Tcl_GetGlobalNamespace', 'Tcl_GetGroupIdFromStat', 'Tcl_GetHashKey',
  779. 'Tcl_GetHashValue', 'Tcl_GetHostName', 'Tcl_GetIndexFromObj', 'Tcl_GetIndexFromObjStruct', 'Tcl_GetInt',
  780. 'Tcl_GetInterpPath', 'Tcl_GetIntFromObj', 'Tcl_GetLinkCountFromStat', 'Tcl_GetLongFromObj',
  781. 'Tcl_GetMaster', 'Tcl_GetMathFuncInfo', 'Tcl_GetModeFromStat', 'Tcl_GetModificationTimeFromStat',
  782. 'Tcl_GetNameOfExecutable', 'Tcl_GetNamespaceUnknownHandler', 'Tcl_GetObjectAsClass', 'Tcl_GetObjectCommand',
  783. 'Tcl_GetObjectFromObj', 'Tcl_GetObjectName', 'Tcl_GetObjectNamespace', 'Tcl_GetObjResult', 'Tcl_GetObjType',
  784. 'Tcl_GetOpenFile', 'Tcl_GetPathType', 'Tcl_GetRange', 'Tcl_GetRegExpFromObj', 'Tcl_GetReturnOptions',
  785. 'Tcl_Gets', 'Tcl_GetServiceMode', 'Tcl_GetSizeFromStat', 'Tcl_GetSlave', 'Tcl_GetsObj',
  786. 'Tcl_GetStackedChannel', 'Tcl_GetStartupScript', 'Tcl_GetStdChannel', 'Tcl_GetString',
  787. 'Tcl_GetStringFromObj', 'Tcl_GetStringResult', 'Tcl_GetThreadData', 'Tcl_GetTime', 'Tcl_GetTopChannel',
  788. 'Tcl_GetUniChar', 'Tcl_GetUnicode', 'Tcl_GetUnicodeFromObj', 'Tcl_GetUserIdFromStat', 'Tcl_GetVar',
  789. 'Tcl_GetVar2', 'Tcl_GetVar2Ex', 'Tcl_GetVersion', 'Tcl_GetWideIntFromObj', 'Tcl_GlobalEval',
  790. 'Tcl_GlobalEvalObj', 'Tcl_GlobTypeData', 'Tcl_HashKeyType', 'Tcl_HashStats', 'Tcl_HideCommand',
  791. 'Tcl_IdleProc', 'Tcl_Import', 'Tcl_IncrRefCount', 'Tcl_Init', 'Tcl_InitCustomHashTable',
  792. 'Tcl_InitHashTable', 'Tcl_InitMemory', 'Tcl_InitNotifier', 'Tcl_InitObjHashTable', 'Tcl_InitStubs',
  793. 'Tcl_InputBlocked', 'Tcl_InputBuffered', 'tcl_interactive', 'Tcl_Interp', 'Tcl_InterpActive',
  794. 'Tcl_InterpDeleted', 'Tcl_InterpDeleteProc', 'Tcl_InvalidateStringRep', 'Tcl_IsChannelExisting',
  795. 'Tcl_IsChannelRegistered', 'Tcl_IsChannelShared', 'Tcl_IsEnsemble', 'Tcl_IsSafe', 'Tcl_IsShared',
  796. 'Tcl_IsStandardChannel', 'Tcl_JoinPath', 'Tcl_JoinThread', 'tcl_library', 'Tcl_LimitAddHandler',
  797. 'Tcl_LimitCheck', 'Tcl_LimitExceeded', 'Tcl_LimitGetCommands', 'Tcl_LimitGetGranularity',
  798. 'Tcl_LimitGetTime', 'Tcl_LimitHandlerDeleteProc', 'Tcl_LimitHandlerProc', 'Tcl_LimitReady',
  799. 'Tcl_LimitRemoveHandler', 'Tcl_LimitSetCommands', 'Tcl_LimitSetGranularity', 'Tcl_LimitSetTime',
  800. 'Tcl_LimitTypeEnabled', 'Tcl_LimitTypeExceeded', 'Tcl_LimitTypeReset', 'Tcl_LimitTypeSet',
  801. 'Tcl_LinkVar', 'Tcl_ListMathFuncs', 'Tcl_ListObjAppendElement', 'Tcl_ListObjAppendList',
  802. 'Tcl_ListObjGetElements', 'Tcl_ListObjIndex', 'Tcl_ListObjLength', 'Tcl_ListObjReplace',
  803. 'Tcl_LogCommandInfo', 'Tcl_Main', 'Tcl_MainLoopProc', 'Tcl_MakeFileChannel', 'Tcl_MakeSafe',
  804. 'Tcl_MakeTcpClientChannel', 'Tcl_MathProc', 'TCL_MEM_DEBUG', 'Tcl_Merge', 'Tcl_MethodCallProc',
  805. 'Tcl_MethodDeclarerClass', 'Tcl_MethodDeclarerObject', 'Tcl_MethodDeleteProc', 'Tcl_MethodIsPublic',
  806. 'Tcl_MethodIsType', 'Tcl_MethodName', 'Tcl_MethodType', 'Tcl_MutexFinalize', 'Tcl_MutexLock',
  807. 'Tcl_MutexUnlock', 'Tcl_NamespaceDeleteProc', 'Tcl_NewBignumObj', 'Tcl_NewBooleanObj',
  808. 'Tcl_NewByteArrayObj', 'Tcl_NewDictObj', 'Tcl_NewDoubleObj', 'Tcl_NewInstanceMethod', 'Tcl_NewIntObj',
  809. 'Tcl_NewListObj', 'Tcl_NewLongObj', 'Tcl_NewMethod', 'Tcl_NewObj', 'Tcl_NewObjectInstance',
  810. 'Tcl_NewStringObj', 'Tcl_NewUnicodeObj', 'Tcl_NewWideIntObj', 'Tcl_NextHashEntry', 'tcl_nonwordchars',
  811. 'Tcl_NotifierProcs', 'Tcl_NotifyChannel', 'Tcl_NRAddCallback', 'Tcl_NRCallObjProc', 'Tcl_NRCmdSwap',
  812. 'Tcl_NRCreateCommand', 'Tcl_NREvalObj', 'Tcl_NREvalObjv', 'Tcl_NumUtfChars', 'Tcl_Obj', 'Tcl_ObjCmdProc',
  813. 'Tcl_ObjectContextInvokeNext', 'Tcl_ObjectContextIsFiltering', 'Tcl_ObjectContextMethod',
  814. 'Tcl_ObjectContextObject', 'Tcl_ObjectContextSkippedArgs', 'Tcl_ObjectDeleted', 'Tcl_ObjectGetMetadata',
  815. 'Tcl_ObjectGetMethodNameMapper', 'Tcl_ObjectMapMethodNameProc', 'Tcl_ObjectMetadataDeleteProc',
  816. 'Tcl_ObjectSetMetadata', 'Tcl_ObjectSetMethodNameMapper', 'Tcl_ObjGetVar2', 'Tcl_ObjPrintf',
  817. 'Tcl_ObjSetVar2', 'Tcl_ObjType', 'Tcl_OpenCommandChannel', 'Tcl_OpenFileChannel', 'Tcl_OpenTcpClient',
  818. 'Tcl_OpenTcpServer', 'Tcl_OutputBuffered', 'Tcl_PackageInitProc', 'Tcl_PackageUnloadProc', 'Tcl_Panic',
  819. 'Tcl_PanicProc', 'Tcl_PanicVA', 'Tcl_ParseArgsObjv', 'Tcl_ParseBraces', 'Tcl_ParseCommand', 'Tcl_ParseExpr',
  820. 'Tcl_ParseQuotedString', 'Tcl_ParseVar', 'Tcl_ParseVarName', 'tcl_patchLevel', 'tcl_pkgPath',
  821. 'Tcl_PkgPresent', 'Tcl_PkgPresentEx', 'Tcl_PkgProvide', 'Tcl_PkgProvideEx', 'Tcl_PkgRequire',
  822. 'Tcl_PkgRequireEx', 'Tcl_PkgRequireProc', 'tcl_platform', 'Tcl_PosixError', 'tcl_precision',
  823. 'Tcl_Preserve', 'Tcl_PrintDouble', 'Tcl_PutEnv', 'Tcl_QueryTimeProc', 'Tcl_QueueEvent', 'tcl_rcFileName',
  824. 'Tcl_Read', 'Tcl_ReadChars', 'Tcl_ReadRaw', 'Tcl_Realloc', 'Tcl_ReapDetachedProcs', 'Tcl_RecordAndEval',
  825. 'Tcl_RecordAndEvalObj', 'Tcl_RegExpCompile', 'Tcl_RegExpExec', 'Tcl_RegExpExecObj', 'Tcl_RegExpGetInfo',
  826. 'Tcl_RegExpIndices', 'Tcl_RegExpInfo', 'Tcl_RegExpMatch', 'Tcl_RegExpMatchObj', 'Tcl_RegExpRange',
  827. 'Tcl_RegisterChannel', 'Tcl_RegisterConfig', 'Tcl_RegisterObjType', 'Tcl_Release', 'Tcl_ResetResult',
  828. 'Tcl_RestoreInterpState', 'Tcl_RestoreResult', 'Tcl_SaveInterpState', 'Tcl_SaveResult', 'Tcl_ScaleTimeProc',
  829. 'Tcl_ScanCountedElement', 'Tcl_ScanElement', 'Tcl_Seek', 'Tcl_ServiceAll', 'Tcl_ServiceEvent',
  830. 'Tcl_ServiceModeHook', 'Tcl_SetAssocData', 'Tcl_SetBignumObj', 'Tcl_SetBooleanObj',
  831. 'Tcl_SetByteArrayLength', 'Tcl_SetByteArrayObj', 'Tcl_SetChannelBufferSize', 'Tcl_SetChannelError',
  832. 'Tcl_SetChannelErrorInterp', 'Tcl_SetChannelOption', 'Tcl_SetCommandInfo', 'Tcl_SetCommandInfoFromToken',
  833. 'Tcl_SetDefaultEncodingDir', 'Tcl_SetDoubleObj', 'Tcl_SetEncodingSearchPath', 'Tcl_SetEnsembleFlags',
  834. 'Tcl_SetEnsembleMappingDict', 'Tcl_SetEnsembleParameterList', 'Tcl_SetEnsembleSubcommandList',
  835. 'Tcl_SetEnsembleUnknownHandler', 'Tcl_SetErrno', 'Tcl_SetErrorCode', 'Tcl_SetErrorCodeVA',
  836. 'Tcl_SetErrorLine', 'Tcl_SetExitProc', 'Tcl_SetFromAnyProc', 'Tcl_SetHashValue', 'Tcl_SetIntObj',
  837. 'Tcl_SetListObj', 'Tcl_SetLongObj', 'Tcl_SetMainLoop', 'Tcl_SetMaxBlockTime',
  838. 'Tcl_SetNamespaceUnknownHandler', 'Tcl_SetNotifier', 'Tcl_SetObjErrorCode', 'Tcl_SetObjLength',
  839. 'Tcl_SetObjResult', 'Tcl_SetPanicProc', 'Tcl_SetRecursionLimit', 'Tcl_SetResult', 'Tcl_SetReturnOptions',
  840. 'Tcl_SetServiceMode', 'Tcl_SetStartupScript', 'Tcl_SetStdChannel', 'Tcl_SetStringObj',
  841. 'Tcl_SetSystemEncoding', 'Tcl_SetTimeProc', 'Tcl_SetTimer', 'Tcl_SetUnicodeObj', 'Tcl_SetVar',
  842. 'Tcl_SetVar2', 'Tcl_SetVar2Ex', 'Tcl_SetWideIntObj', 'Tcl_SignalId', 'Tcl_SignalMsg', 'Tcl_Sleep',
  843. 'Tcl_SourceRCFile', 'Tcl_SpliceChannel', 'Tcl_SplitList', 'Tcl_SplitPath', 'Tcl_StackChannel',
  844. 'Tcl_StandardChannels', 'tcl_startOfNextWord', 'tcl_startOfPreviousWord', 'Tcl_Stat', 'Tcl_StaticPackage',
  845. 'Tcl_StringCaseMatch', 'Tcl_StringMatch', 'Tcl_SubstObj', 'Tcl_TakeBignumFromObj', 'Tcl_TcpAcceptProc',
  846. 'Tcl_Tell', 'Tcl_ThreadAlert', 'Tcl_ThreadQueueEvent', 'Tcl_Time', 'Tcl_TimerProc', 'Tcl_Token',
  847. 'Tcl_TraceCommand', 'tcl_traceCompile', 'tcl_traceEval', 'Tcl_TraceVar', 'Tcl_TraceVar2',
  848. 'Tcl_TransferResult', 'Tcl_TranslateFileName', 'Tcl_TruncateChannel', 'Tcl_Ungets', 'Tcl_UniChar',
  849. 'Tcl_UniCharAtIndex', 'Tcl_UniCharCaseMatch', 'Tcl_UniCharIsAlnum', 'Tcl_UniCharIsAlpha',
  850. 'Tcl_UniCharIsControl', 'Tcl_UniCharIsDigit', 'Tcl_UniCharIsGraph', 'Tcl_UniCharIsLower',
  851. 'Tcl_UniCharIsPrint', 'Tcl_UniCharIsPunct', 'Tcl_UniCharIsSpace', 'Tcl_UniCharIsUpper',
  852. 'Tcl_UniCharIsWordChar', 'Tcl_UniCharLen', 'Tcl_UniCharNcasecmp', 'Tcl_UniCharNcmp', 'Tcl_UniCharToLower',
  853. 'Tcl_UniCharToTitle', 'Tcl_UniCharToUpper', 'Tcl_UniCharToUtf', 'Tcl_UniCharToUtfDString', 'Tcl_UnlinkVar',
  854. 'Tcl_UnregisterChannel', 'Tcl_UnsetVar', 'Tcl_UnsetVar2', 'Tcl_UnstackChannel', 'Tcl_UntraceCommand',
  855. 'Tcl_UntraceVar', 'Tcl_UntraceVar2', 'Tcl_UpdateLinkedVar', 'Tcl_UpdateStringProc', 'Tcl_UpVar',
  856. 'Tcl_UpVar2', 'Tcl_UtfAtIndex', 'Tcl_UtfBackslash', 'Tcl_UtfCharComplete', 'Tcl_UtfFindFirst',
  857. 'Tcl_UtfFindLast', 'Tcl_UtfNext', 'Tcl_UtfPrev', 'Tcl_UtfToExternal', 'Tcl_UtfToExternalDString',
  858. 'Tcl_UtfToLower', 'Tcl_UtfToTitle', 'Tcl_UtfToUniChar', 'Tcl_UtfToUniCharDString', 'Tcl_UtfToUpper',
  859. 'Tcl_ValidateAllMemory', 'Tcl_Value', 'Tcl_VarEval', 'Tcl_VarEvalVA', 'Tcl_VarTraceInfo',
  860. 'Tcl_VarTraceInfo2', 'Tcl_VarTraceProc', 'tcl_version', 'Tcl_WaitForEvent', 'Tcl_WaitPid',
  861. 'Tcl_WinTCharToUtf', 'Tcl_WinUtfToTChar', 'tcl_wordBreakAfter', 'tcl_wordBreakBefore', 'tcl_wordchars',
  862. 'Tcl_Write', 'Tcl_WriteChars', 'Tcl_WriteObj', 'Tcl_WriteRaw', 'Tcl_WrongNumArgs', 'Tcl_ZlibAdler32',
  863. 'Tcl_ZlibCRC32', 'Tcl_ZlibDeflate', 'Tcl_ZlibInflate', 'Tcl_ZlibStreamChecksum', 'Tcl_ZlibStreamClose',
  864. 'Tcl_ZlibStreamEof', 'Tcl_ZlibStreamGet', 'Tcl_ZlibStreamGetCommandName', 'Tcl_ZlibStreamInit',
  865. 'Tcl_ZlibStreamPut', 'tcltest', 'tell', 'throw', 'time', 'tm', 'trace', 'transchan', 'try', 'unknown',
  866. 'unload', 'unset', 'update', 'uplevel', 'upvar', 'variable', 'vwait', 'while', 'yield', 'yieldto', 'zlib'
  867. ]
  868. self.autocomplete_kw_list = self.defaults['util_autocomplete_keywords'].replace(' ', '').split(',')
  869. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  870. # ###########################################################################################################
  871. # ########################################## Tools and Plugins ##############################################
  872. # ###########################################################################################################
  873. self.shell = None
  874. self.dblsidedtool = None
  875. self.distance_tool = None
  876. self.distance_min_tool = None
  877. self.panelize_tool = None
  878. self.film_tool = None
  879. self.paste_tool = None
  880. self.calculator_tool = None
  881. self.rules_tool = None
  882. self.sub_tool = None
  883. self.move_tool = None
  884. self.cutout_tool = None
  885. self.ncclear_tool = None
  886. self.paint_tool = None
  887. self.isolation_tool = None
  888. self.drilling_tool = None
  889. self.optimal_tool = None
  890. self.transform_tool = None
  891. self.properties_tool = None
  892. self.pdf_tool = None
  893. self.image_tool = None
  894. self.pcb_wizard_tool = None
  895. self.cal_exc_tool = None
  896. self.qrcode_tool = None
  897. self.copper_thieving_tool = None
  898. self.fiducial_tool = None
  899. self.edrills_tool = None
  900. self.align_objects_tool = None
  901. self.punch_tool = None
  902. self.invert_tool = None
  903. self.corners_tool = None
  904. self.etch_tool = None
  905. # always install tools only after the shell is initialized because the self.inform.emit() depends on shell
  906. try:
  907. self.install_tools()
  908. except AttributeError as e:
  909. log.debug("App.__init__() install_tools() --> %s" % str(e))
  910. # ###########################################################################################################
  911. # ######################################### BookMarks Manager ###############################################
  912. # ###########################################################################################################
  913. # install Bookmark Manager and populate bookmarks in the Help -> Bookmarks
  914. self.install_bookmarks()
  915. self.book_dialog_tab = BookmarkManager(app=self, storage=self.defaults["global_bookmarks"])
  916. # ###########################################################################################################
  917. # ########################################### Tools Database ################################################
  918. # ###########################################################################################################
  919. self.tools_db_tab = None
  920. # ### System Font Parsing ###
  921. # self.f_parse = ParseFont(self)
  922. # self.parse_system_fonts()
  923. # ###########################################################################################################
  924. # ############################################## Shell SETUP ################################################
  925. # ###########################################################################################################
  926. # show TCL shell at start-up based on the Menu -? Edit -> Preferences setting.
  927. if self.defaults["global_shell_at_startup"]:
  928. self.ui.shell_dock.show()
  929. else:
  930. self.ui.shell_dock.hide()
  931. # ###########################################################################################################
  932. # ######################################### Check for updates ###############################################
  933. # ###########################################################################################################
  934. # Separate thread (Not worker)
  935. # Check for updates on startup but only if the user consent and the app is not in Beta version
  936. if (self.beta is False or self.beta is None) and \
  937. self.ui.general_defaults_form.general_app_group.version_check_cb.get_value() is True:
  938. App.log.info("Checking for updates in backgroud (this is version %s)." % str(self.version))
  939. # self.thr2 = QtCore.QThread()
  940. self.worker_task.emit({'fcn': self.version_check,
  941. 'params': []})
  942. # self.thr2.start(QtCore.QThread.LowPriority)
  943. # ###########################################################################################################
  944. # ##################################### Register files with FlatCAM; #######################################
  945. # ################################### It works only for Windows for now ####################################
  946. # ###########################################################################################################
  947. if sys.platform == 'win32' and self.defaults["first_run"] is True:
  948. self.on_register_files()
  949. # ###########################################################################################################
  950. # ######################################## Variables for global usage #######################################
  951. # ###########################################################################################################
  952. # hold the App units
  953. self.units = 'MM'
  954. # coordinates for relative position display
  955. self.rel_point1 = (0, 0)
  956. self.rel_point2 = (0, 0)
  957. # variable to store coordinates
  958. self.pos = (0, 0)
  959. self.pos_canvas = (0, 0)
  960. self.pos_jump = (0, 0)
  961. # variable to store mouse coordinates
  962. self.mouse = [0, 0]
  963. # variable to store the delta positions on cavnas
  964. self.dx = 0
  965. self.dy = 0
  966. # decide if we have a double click or single click
  967. self.doubleclick = False
  968. # store here the is_dragging value
  969. self.event_is_dragging = False
  970. # variable to store if a command is active (then the var is not None) and which one it is
  971. self.command_active = None
  972. # variable to store the status of moving selection action
  973. # None value means that it's not an selection action
  974. # True value = a selection from left to right
  975. # False value = a selection from right to left
  976. self.selection_type = None
  977. # List to store the objects that are currently loaded in FlatCAM
  978. # This list is updated on each object creation or object delete
  979. self.all_objects_list = []
  980. self.objects_under_the_click_list = []
  981. # List to store the objects that are selected
  982. self.sel_objects_list = []
  983. # holds the key modifier if pressed (CTRL, SHIFT or ALT)
  984. self.key_modifiers = None
  985. # Variable to store the status of the code editor
  986. self.toggle_codeeditor = False
  987. # Variable to be used for situations when we don't want the LMB click on canvas to auto open the Project Tab
  988. self.click_noproject = False
  989. self.cursor = None
  990. # Variable to store the GCODE that was edited
  991. self.gcode_edited = ""
  992. # Variable to store old state of the Tools Toolbar; used in the Editor2Object and in Object2Editor methods
  993. self.old_state_of_tools_toolbar = False
  994. self.text_editor_tab = None
  995. # reference for the self.ui.code_editor
  996. self.reference_code_editor = None
  997. self.script_code = ''
  998. # if Tools DB are changed/edited in the Edit -> Tools Database tab the value will be set to True
  999. self.tools_db_changed_flag = False
  1000. self.grb_list = ['art', 'bot', 'bsm', 'cmp', 'crc', 'crs', 'dim', 'g4', 'gb0', 'gb1', 'gb2', 'gb3', 'gb5',
  1001. 'gb6', 'gb7', 'gb8', 'gb9', 'gbd', 'gbl', 'gbo', 'gbp', 'gbr', 'gbs', 'gdo', 'ger', 'gko',
  1002. 'gml', 'gm1', 'gm2', 'gm3', 'grb', 'gtl', 'gto', 'gtp', 'gts', 'ly15', 'ly2', 'mil', 'outline',
  1003. 'pho', 'plc', 'pls', 'smb', 'smt', 'sol', 'spb', 'spt', 'ssb', 'sst', 'stc', 'sts', 'top',
  1004. 'tsm']
  1005. self.exc_list = ['drd', 'drl', 'drill', 'exc', 'ncd', 'tap', 'txt', 'xln']
  1006. self.gcode_list = ['cnc', 'din', 'dnc', 'ecs', 'eia', 'fan', 'fgc', 'fnc', 'gc', 'gcd', 'gcode', 'h', 'hnc',
  1007. 'i', 'min', 'mpf', 'mpr', 'nc', 'ncc', 'ncg', 'ngc', 'ncp', 'out', 'ply', 'rol',
  1008. 'sbp', 'tap', 'xpi']
  1009. self.svg_list = ['svg']
  1010. self.dxf_list = ['dxf']
  1011. self.pdf_list = ['pdf']
  1012. self.prj_list = ['flatprj']
  1013. self.conf_list = ['flatconfig']
  1014. # last used filters
  1015. self.last_op_gerber_filter = None
  1016. self.last_op_excellon_filter = None
  1017. self.last_op_gcode_filter = None
  1018. # global variable used by NCC Tool to signal that some polygons could not be cleared, if True
  1019. # flag for polygons not cleared
  1020. self.poly_not_cleared = False
  1021. # VisPy visuals
  1022. self.isHovering = False
  1023. self.notHovering = True
  1024. # Window geometry
  1025. self.x_pos = None
  1026. self.y_pos = None
  1027. self.width = None
  1028. self.height = None
  1029. # when True, the app has to return from any thread
  1030. self.abort_flag = False
  1031. # set the value used in the Windows Title
  1032. self.engine = self.ui.general_defaults_form.general_app_group.ge_radio.get_value()
  1033. # this holds a widget that is installed in the Plot Area when View Source option is used
  1034. self.source_editor_tab = None
  1035. self.pagesize = {}
  1036. # Storage for shapes, storage that can be used by FlatCAm tools for utility geometry
  1037. # VisPy visuals
  1038. if self.is_legacy is False:
  1039. try:
  1040. self.tool_shapes = ShapeCollection(parent=self.plotcanvas.view.scene, layers=1)
  1041. except AttributeError:
  1042. self.tool_shapes = None
  1043. else:
  1044. from appGUI.PlotCanvasLegacy import ShapeCollectionLegacy
  1045. self.tool_shapes = ShapeCollectionLegacy(obj=self, app=self, name="tool")
  1046. # used in the delayed shutdown self.start_delayed_quit() method
  1047. self.save_timer = None
  1048. # ###########################################################################################################
  1049. # ################################## ADDING FlatCAM EDITORS section #########################################
  1050. # ###########################################################################################################
  1051. # watch out for the position of the editors instantiation ... if it is done before a save of the default values
  1052. # at the first launch of the App , the editors will not be functional.
  1053. try:
  1054. self.geo_editor = AppGeoEditor(self)
  1055. except Exception as es:
  1056. log.debug("app_Main.__init__() --> Geo Editor Error: %s" % str(es))
  1057. try:
  1058. self.exc_editor = AppExcEditor(self)
  1059. except Exception as es:
  1060. log.debug("app_Main.__init__() --> Excellon Editor Error: %s" % str(es))
  1061. try:
  1062. self.grb_editor = AppGerberEditor(self)
  1063. except Exception as es:
  1064. log.debug("app_Main.__init__() --> Gerber Editor Error: %s" % str(es))
  1065. try:
  1066. self.gcode_editor = AppGCodeEditor(self)
  1067. except Exception as es:
  1068. log.debug("app_Main.__init__() --> GCode Editor Error: %s" % str(es))
  1069. self.log.debug("Finished adding FlatCAM Editor's.")
  1070. self.set_ui_title(name=_("New Project - Not saved"))
  1071. current_platform = platform.architecture()[0]
  1072. if current_platform != '64bit':
  1073. # set Excellon path optimizations algorithm to TSA if the app is run on a 32bit platform
  1074. # modes 'M' or 'B' are not allowed when the app is running in 32bit platform
  1075. if self.defaults['excellon_optimization_type'] in ['M', 'B']:
  1076. self.ui.excellon_defaults_form.excellon_gen_group.excellon_optimization_radio.set_value('T')
  1077. # set Geometry path optimizations algorithm to Rtree if the app is run on a 32bit platform
  1078. # modes 'M' or 'B' are not allowed when the app is running in 32bit platform
  1079. if self.defaults['geometry_optimization_type'] in ['M', 'B']:
  1080. self.ui.geometry_defaults_form.geometry_gen_group.opt_algorithm_radio.set_value('R')
  1081. # ###########################################################################################################
  1082. # ########################################### EXCLUSION AREAS ###############################################
  1083. # ###########################################################################################################
  1084. self.exc_areas = ExclusionAreas(app=self)
  1085. # ###########################################################################################################
  1086. # ###########################################################################################################
  1087. # ###################################### INSTANTIATE CLASSES THAT HOLD THE MENU HANDLERS ####################
  1088. # ###########################################################################################################
  1089. # ###########################################################################################################
  1090. self.f_handlers = MenuFileHandlers(app=self)
  1091. # this is calculated in the class above (somehow?)
  1092. self.defaults["root_folder_path"] = self.app_home
  1093. # ###########################################################################################################
  1094. # ############################################ SETUP RECENT ITEMS ###########################################
  1095. # ###########################################################################################################
  1096. self.setup_recent_items()
  1097. # ###########################################################################################################
  1098. # ###########################################################################################################
  1099. # ############################################# Signal handling #############################################
  1100. # ###########################################################################################################
  1101. # ###########################################################################################################
  1102. # ########################################## Custom signals ################################################
  1103. # signal for displaying messages in status bar
  1104. self.inform[str].connect(self.info)
  1105. self.inform[str, bool].connect(self.info)
  1106. # signal for displaying messages in the shell
  1107. self.inform_shell[str].connect(self.info_shell)
  1108. self.inform_shell[str, bool].connect(self.info_shell)
  1109. # signal to be called when the app is quiting
  1110. self.app_quit.connect(self.quit_application, type=Qt.QueuedConnection)
  1111. self.message.connect(lambda: message_dialog(parent=self.ui))
  1112. # self.progress.connect(self.set_progress_bar)
  1113. # signals emitted when file state change
  1114. self.file_opened.connect(self.register_recent)
  1115. self.file_opened.connect(lambda kind, filename: self.register_folder(filename))
  1116. self.file_saved.connect(lambda kind, filename: self.register_save_folder(filename))
  1117. # when the defaults dictionary values change
  1118. self.defaults.defaults.set_change_callback(callback=self.on_properties_tab_click)
  1119. # ########################################## Standard signals ###############################################
  1120. # ### Menu
  1121. self.ui.menufilenewproject.triggered.connect(self.f_handlers.on_file_new_click)
  1122. self.ui.menufilenewgeo.triggered.connect(self.app_obj.new_geometry_object)
  1123. self.ui.menufilenewgrb.triggered.connect(self.app_obj.new_gerber_object)
  1124. self.ui.menufilenewexc.triggered.connect(self.app_obj.new_excellon_object)
  1125. self.ui.menufilenewdoc.triggered.connect(self.app_obj.new_document_object)
  1126. self.ui.menufileopengerber.triggered.connect(self.f_handlers.on_fileopengerber)
  1127. self.ui.menufileopenexcellon.triggered.connect(self.f_handlers.on_fileopenexcellon)
  1128. self.ui.menufileopengcode.triggered.connect(self.f_handlers.on_fileopengcode)
  1129. self.ui.menufileopenproject.triggered.connect(self.f_handlers.on_file_openproject)
  1130. self.ui.menufileopenconfig.triggered.connect(self.f_handlers.on_file_openconfig)
  1131. self.ui.menufilenewscript.triggered.connect(self.f_handlers.on_filenewscript)
  1132. self.ui.menufileopenscript.triggered.connect(self.f_handlers.on_fileopenscript)
  1133. self.ui.menufileopenscriptexample.triggered.connect(self.f_handlers.on_fileopenscript_example)
  1134. self.ui.menufilerunscript.triggered.connect(self.f_handlers.on_filerunscript)
  1135. self.ui.menufileimportsvg.triggered.connect(lambda: self.f_handlers.on_file_importsvg("geometry"))
  1136. self.ui.menufileimportsvg_as_gerber.triggered.connect(lambda: self.f_handlers.on_file_importsvg("gerber"))
  1137. self.ui.menufileimportdxf.triggered.connect(lambda: self.f_handlers.on_file_importdxf("geometry"))
  1138. self.ui.menufileimportdxf_as_gerber.triggered.connect(lambda: self.f_handlers.on_file_importdxf("gerber"))
  1139. self.ui.menufileimport_hpgl2_as_geo.triggered.connect(self.f_handlers.on_fileopenhpgl2)
  1140. self.ui.menufileexportsvg.triggered.connect(self.f_handlers.on_file_exportsvg)
  1141. self.ui.menufileexportpng.triggered.connect(self.f_handlers.on_file_exportpng)
  1142. self.ui.menufileexportexcellon.triggered.connect(self.f_handlers.on_file_exportexcellon)
  1143. self.ui.menufileexportgerber.triggered.connect(self.f_handlers.on_file_exportgerber)
  1144. self.ui.menufileexportdxf.triggered.connect(self.f_handlers.on_file_exportdxf)
  1145. self.ui.menufile_print.triggered.connect(lambda: self.f_handlers.on_file_save_objects_pdf(use_thread=True))
  1146. self.ui.menufilesaveproject.triggered.connect(self.f_handlers.on_file_saveproject)
  1147. self.ui.menufilesaveprojectas.triggered.connect(self.f_handlers.on_file_saveprojectas)
  1148. # self.ui.menufilesaveprojectcopy.triggered.connect(lambda: self.on_file_saveprojectas(make_copy=True))
  1149. self.ui.menufilesavedefaults.triggered.connect(self.f_handlers.on_file_savedefaults)
  1150. self.ui.menufileexportpref.triggered.connect(self.f_handlers.on_export_preferences)
  1151. self.ui.menufileimportpref.triggered.connect(self.f_handlers.on_import_preferences)
  1152. self.ui.menufile_exit.triggered.connect(self.final_save)
  1153. self.ui.menueditedit.triggered.connect(lambda: self.object2editor())
  1154. self.ui.menueditok.triggered.connect(lambda: self.editor2object())
  1155. self.ui.menuedit_join2geo.triggered.connect(self.on_edit_join)
  1156. self.ui.menuedit_join_exc2exc.triggered.connect(self.on_edit_join_exc)
  1157. self.ui.menuedit_join_grb2grb.triggered.connect(self.on_edit_join_grb)
  1158. self.ui.menuedit_convert_sg2mg.triggered.connect(self.on_convert_singlegeo_to_multigeo)
  1159. self.ui.menuedit_convert_mg2sg.triggered.connect(self.on_convert_multigeo_to_singlegeo)
  1160. self.ui.menueditdelete.triggered.connect(self.on_delete)
  1161. self.ui.menueditcopyobject.triggered.connect(self.on_copy_command)
  1162. self.ui.menueditconvert_any2geo.triggered.connect(self.convert_any2geo)
  1163. self.ui.menueditconvert_any2gerber.triggered.connect(self.convert_any2gerber)
  1164. self.ui.menueditconvert_any2excellon.triggered.connect(self.convert_any2excellon)
  1165. self.ui.menueditorigin.triggered.connect(self.on_set_origin)
  1166. self.ui.menuedit_move2origin.triggered.connect(self.on_move2origin)
  1167. self.ui.menueditjump.triggered.connect(self.on_jump_to)
  1168. self.ui.menueditlocate.triggered.connect(lambda: self.on_locate(obj=self.collection.get_active()))
  1169. self.ui.menuedittoggleunits.triggered.connect(self.on_toggle_units_click)
  1170. self.ui.menueditselectall.triggered.connect(self.on_selectall)
  1171. self.ui.menueditpreferences.triggered.connect(self.on_preferences)
  1172. # self.ui.menuoptions_transfer_a2o.triggered.connect(self.on_options_app2object)
  1173. # self.ui.menuoptions_transfer_a2p.triggered.connect(self.on_options_app2project)
  1174. # self.ui.menuoptions_transfer_o2a.triggered.connect(self.on_options_object2app)
  1175. # self.ui.menuoptions_transfer_p2a.triggered.connect(self.on_options_project2app)
  1176. # self.ui.menuoptions_transfer_o2p.triggered.connect(self.on_options_object2project)
  1177. # self.ui.menuoptions_transfer_p2o.triggered.connect(self.on_options_project2object)
  1178. self.ui.menuoptions_transform_rotate.triggered.connect(self.on_rotate)
  1179. self.ui.menuoptions_transform_skewx.triggered.connect(self.on_skewx)
  1180. self.ui.menuoptions_transform_skewy.triggered.connect(self.on_skewy)
  1181. self.ui.menuoptions_transform_flipx.triggered.connect(self.on_flipx)
  1182. self.ui.menuoptions_transform_flipy.triggered.connect(self.on_flipy)
  1183. self.ui.menuoptions_view_source.triggered.connect(self.on_view_source)
  1184. self.ui.menuoptions_tools_db.triggered.connect(lambda: self.on_tools_database(source='app'))
  1185. self.ui.menuviewdisableall.triggered.connect(self.disable_all_plots)
  1186. self.ui.menuviewdisableother.triggered.connect(self.disable_other_plots)
  1187. self.ui.menuviewenable.triggered.connect(self.enable_all_plots)
  1188. self.ui.menuview_zoom_fit.triggered.connect(self.on_zoom_fit)
  1189. self.ui.menuview_zoom_in.triggered.connect(self.on_zoom_in)
  1190. self.ui.menuview_zoom_out.triggered.connect(self.on_zoom_out)
  1191. self.ui.menuview_replot.triggered.connect(self.plot_all)
  1192. self.ui.menuview_toggle_code_editor.triggered.connect(self.on_toggle_code_editor)
  1193. self.ui.menuview_toggle_fscreen.triggered.connect(self.ui.on_fullscreen)
  1194. self.ui.menuview_toggle_parea.triggered.connect(self.ui.on_toggle_plotarea)
  1195. self.ui.menuview_toggle_notebook.triggered.connect(self.ui.on_toggle_notebook)
  1196. self.ui.menu_toggle_nb.triggered.connect(self.ui.on_toggle_notebook)
  1197. self.ui.menuview_toggle_grid.triggered.connect(self.ui.on_toggle_grid)
  1198. self.ui.menuview_toggle_workspace.triggered.connect(self.on_workspace_toggle)
  1199. self.ui.menuview_toggle_grid_lines.triggered.connect(self.plotcanvas.on_toggle_grid_lines)
  1200. self.ui.menuview_toggle_axis.triggered.connect(self.plotcanvas.on_toggle_axis)
  1201. self.ui.menuview_toggle_hud.triggered.connect(self.plotcanvas.on_toggle_hud)
  1202. self.ui.menutoolshell.triggered.connect(self.ui.toggle_shell_ui)
  1203. self.ui.menuhelp_about.triggered.connect(self.on_about)
  1204. self.ui.menuhelp_readme.triggered.connect(self.on_readme)
  1205. self.ui.menuhelp_manual.triggered.connect(lambda: webbrowser.open(self.manual_url))
  1206. self.ui.menuhelp_report_bug.triggered.connect(lambda: webbrowser.open(self.bug_report_url))
  1207. self.ui.menuhelp_exc_spec.triggered.connect(lambda: webbrowser.open(self.excellon_spec_url))
  1208. self.ui.menuhelp_gerber_spec.triggered.connect(lambda: webbrowser.open(self.gerber_spec_url))
  1209. self.ui.menuhelp_videohelp.triggered.connect(lambda: webbrowser.open(self.video_url))
  1210. self.ui.menuhelp_shortcut_list.triggered.connect(self.on_shortcut_list)
  1211. self.ui.menuprojectenable.triggered.connect(self.on_enable_sel_plots)
  1212. self.ui.menuprojectdisable.triggered.connect(self.on_disable_sel_plots)
  1213. self.ui.menuprojectgeneratecnc.triggered.connect(lambda: self.generate_cnc_job(self.collection.get_selected()))
  1214. self.ui.menuprojectviewsource.triggered.connect(self.on_view_source)
  1215. self.ui.menuprojectcopy.triggered.connect(self.on_copy_command)
  1216. self.ui.menuprojectedit.triggered.connect(self.object2editor)
  1217. self.ui.menuprojectdelete.triggered.connect(self.on_delete)
  1218. self.ui.menuprojectsave.triggered.connect(self.on_project_context_save)
  1219. self.ui.menuprojectproperties.triggered.connect(self.obj_properties)
  1220. # ToolBar signals
  1221. self.connect_toolbar_signals(ui=self.ui)
  1222. # Context Menu
  1223. self.ui.popmenu_disable.triggered.connect(lambda: self.toggle_plots(self.collection.get_selected()))
  1224. self.ui.popmenu_panel_toggle.triggered.connect(self.ui.on_toggle_notebook)
  1225. self.ui.popmenu_new_geo.triggered.connect(self.app_obj.new_geometry_object)
  1226. self.ui.popmenu_new_grb.triggered.connect(self.app_obj.new_gerber_object)
  1227. self.ui.popmenu_new_exc.triggered.connect(self.app_obj.new_excellon_object)
  1228. self.ui.popmenu_new_prj.triggered.connect(self.f_handlers.on_file_new)
  1229. self.ui.zoomfit.triggered.connect(self.on_zoom_fit)
  1230. self.ui.clearplot.triggered.connect(self.clear_plots)
  1231. self.ui.replot.triggered.connect(self.plot_all)
  1232. self.ui.popmenu_copy.triggered.connect(self.on_copy_command)
  1233. self.ui.popmenu_delete.triggered.connect(self.on_delete)
  1234. self.ui.popmenu_edit.triggered.connect(self.object2editor)
  1235. self.ui.popmenu_save.triggered.connect(lambda: self.editor2object())
  1236. self.ui.popmenu_move.triggered.connect(self.obj_move)
  1237. self.ui.popmenu_properties.triggered.connect(self.obj_properties)
  1238. # Project Context Menu -> Color Setting
  1239. for act in self.ui.menuprojectcolor.actions():
  1240. act.triggered.connect(self.on_set_color_action_triggered)
  1241. # Notebook tab clicking
  1242. self.ui.notebook.tabBarClicked.connect(self.on_properties_tab_click)
  1243. # ###########################################################################################################
  1244. # #################################### GUI PREFERENCES SIGNALS ##############################################
  1245. # ###########################################################################################################
  1246. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.connect(
  1247. lambda: self.on_toggle_units(no_pref=False))
  1248. # ##################################### Workspace Setting Signals ###########################################
  1249. self.ui.general_defaults_form.general_app_set_group.wk_cb.currentIndexChanged.connect(
  1250. self.on_workspace_modified)
  1251. self.ui.general_defaults_form.general_app_set_group.wk_orientation_radio.activated_custom.connect(
  1252. self.on_workspace_modified
  1253. )
  1254. self.ui.general_defaults_form.general_app_set_group.workspace_cb.stateChanged.connect(self.on_workspace)
  1255. # ###########################################################################################################
  1256. # ######################################## GUI SETTINGS SIGNALS #############################################
  1257. # ###########################################################################################################
  1258. self.ui.general_defaults_form.general_app_set_group.cursor_radio.activated_custom.connect(self.on_cursor_type)
  1259. # ######################################## Tools related signals ############################################
  1260. # portability changed signal
  1261. self.ui.general_defaults_form.general_app_group.portability_cb.stateChanged.connect(self.on_portable_checked)
  1262. # Object list
  1263. self.object_status_changed.connect(self.collection.on_collection_updated)
  1264. # when there are arguments at application startup this get launched
  1265. self.args_at_startup[list].connect(self.on_startup_args)
  1266. # ###########################################################################################################
  1267. # ####################################### FILE ASSOCIATIONS SIGNALS #########################################
  1268. # ###########################################################################################################
  1269. self.ui.util_defaults_form.fa_excellon_group.restore_btn.clicked.connect(
  1270. lambda: self.restore_extensions(ext_type='excellon'))
  1271. self.ui.util_defaults_form.fa_gcode_group.restore_btn.clicked.connect(
  1272. lambda: self.restore_extensions(ext_type='gcode'))
  1273. self.ui.util_defaults_form.fa_gerber_group.restore_btn.clicked.connect(
  1274. lambda: self.restore_extensions(ext_type='gerber'))
  1275. self.ui.util_defaults_form.fa_excellon_group.del_all_btn.clicked.connect(
  1276. lambda: self.delete_all_extensions(ext_type='excellon'))
  1277. self.ui.util_defaults_form.fa_gcode_group.del_all_btn.clicked.connect(
  1278. lambda: self.delete_all_extensions(ext_type='gcode'))
  1279. self.ui.util_defaults_form.fa_gerber_group.del_all_btn.clicked.connect(
  1280. lambda: self.delete_all_extensions(ext_type='gerber'))
  1281. self.ui.util_defaults_form.fa_excellon_group.add_btn.clicked.connect(
  1282. lambda: self.add_extension(ext_type='excellon'))
  1283. self.ui.util_defaults_form.fa_gcode_group.add_btn.clicked.connect(
  1284. lambda: self.add_extension(ext_type='gcode'))
  1285. self.ui.util_defaults_form.fa_gerber_group.add_btn.clicked.connect(
  1286. lambda: self.add_extension(ext_type='gerber'))
  1287. self.ui.util_defaults_form.fa_excellon_group.del_btn.clicked.connect(
  1288. lambda: self.del_extension(ext_type='excellon'))
  1289. self.ui.util_defaults_form.fa_gcode_group.del_btn.clicked.connect(
  1290. lambda: self.del_extension(ext_type='gcode'))
  1291. self.ui.util_defaults_form.fa_gerber_group.del_btn.clicked.connect(
  1292. lambda: self.del_extension(ext_type='gerber'))
  1293. # connect the 'Apply' buttons from the Preferences/File Associations
  1294. self.ui.util_defaults_form.fa_excellon_group.exc_list_btn.clicked.connect(
  1295. lambda: self.on_register_files(obj_type='excellon'))
  1296. self.ui.util_defaults_form.fa_gcode_group.gco_list_btn.clicked.connect(
  1297. lambda: self.on_register_files(obj_type='gcode'))
  1298. self.ui.util_defaults_form.fa_gerber_group.grb_list_btn.clicked.connect(
  1299. lambda: self.on_register_files(obj_type='gerber'))
  1300. # ###########################################################################################################
  1301. # ########################################### KEYWORDS SIGNALS ##############################################
  1302. # ###########################################################################################################
  1303. self.ui.util_defaults_form.kw_group.restore_btn.clicked.connect(
  1304. lambda: self.restore_extensions(ext_type='keyword'))
  1305. self.ui.util_defaults_form.kw_group.del_all_btn.clicked.connect(
  1306. lambda: self.delete_all_extensions(ext_type='keyword'))
  1307. self.ui.util_defaults_form.kw_group.add_btn.clicked.connect(
  1308. lambda: self.add_extension(ext_type='keyword'))
  1309. self.ui.util_defaults_form.kw_group.del_btn.clicked.connect(
  1310. lambda: self.del_extension(ext_type='keyword'))
  1311. # ###########################################################################################################
  1312. # ########################################### GUI SIGNALS ###################################################
  1313. # ###########################################################################################################
  1314. self.ui.hud_label.clicked.connect(self.plotcanvas.on_toggle_hud)
  1315. self.ui.axis_status_label.clicked.connect(self.plotcanvas.on_toggle_axis)
  1316. self.ui.pref_status_label.clicked.connect(self.on_toggle_preferences)
  1317. # ###########################################################################################################
  1318. # ####################################### VARIOUS SIGNALS ###################################################
  1319. # ###########################################################################################################
  1320. # connect the abort_all_tasks related slots to the related signals
  1321. self.proc_container.idle_flag.connect(self.app_is_idle)
  1322. # signal emitted when a tab is closed in the Plot Area
  1323. self.ui.plot_tab_area.tab_closed_signal.connect(self.on_plot_area_tab_closed)
  1324. # signal to close the application
  1325. self.close_app_signal.connect(self.kill_app)
  1326. # ################################# FINISHED CONNECTING SIGNALS #############################################
  1327. # ###########################################################################################################
  1328. # ###########################################################################################################
  1329. # ###########################################################################################################
  1330. self.log.debug("Finished connecting Signals.")
  1331. # ###########################################################################################################
  1332. # ##################################### Finished the CONSTRUCTOR ############################################
  1333. # ###########################################################################################################
  1334. App.log.debug("END of constructor. Releasing control.")
  1335. # ###########################################################################################################
  1336. # ########################################## SHOW GUI #######################################################
  1337. # ###########################################################################################################
  1338. # if the app is not started as headless, show it
  1339. if self.cmd_line_headless != 1:
  1340. if show_splash:
  1341. # finish the splash
  1342. self.splash.finish(self.ui)
  1343. mgui_settings = QSettings("Open Source", "FlatCAM")
  1344. if mgui_settings.contains("maximized_gui"):
  1345. maximized_ui = mgui_settings.value('maximized_gui', type=bool)
  1346. if maximized_ui is True:
  1347. self.ui.showMaximized()
  1348. else:
  1349. self.ui.show()
  1350. else:
  1351. self.ui.show()
  1352. if self.defaults["global_systray_icon"]:
  1353. self.trayIcon.show()
  1354. else:
  1355. log.warning("******************* RUNNING HEADLESS *******************")
  1356. # ###########################################################################################################
  1357. # ######################################## START-UP ARGUMENTS ###############################################
  1358. # ###########################################################################################################
  1359. # test if the program was started with a script as parameter
  1360. if self.cmd_line_shellvar:
  1361. try:
  1362. cnt = 0
  1363. command_tcl = 0
  1364. for i in self.cmd_line_shellvar.split(','):
  1365. if i is not None:
  1366. # noinspection PyBroadException
  1367. try:
  1368. command_tcl = eval(i)
  1369. except Exception:
  1370. command_tcl = i
  1371. command_tcl_formatted = 'set shellvar_{nr} "{cmd}"'.format(cmd=str(command_tcl), nr=str(cnt))
  1372. cnt += 1
  1373. # if there are Windows paths then replace the path separator with a Unix like one
  1374. if sys.platform == 'win32':
  1375. command_tcl_formatted = command_tcl_formatted.replace('\\', '/')
  1376. self.shell.exec_command(command_tcl_formatted, no_echo=True)
  1377. except Exception as ext:
  1378. print("ERROR: ", ext)
  1379. sys.exit(2)
  1380. if self.cmd_line_shellfile:
  1381. if self.cmd_line_headless != 1:
  1382. if self.ui.shell_dock.isHidden():
  1383. self.ui.shell_dock.show()
  1384. try:
  1385. with open(self.cmd_line_shellfile, "r") as myfile:
  1386. # if show_splash:
  1387. # self.splash.showMessage('%s: %ssec\n%s' % (
  1388. # _("Canvas initialization started.\n"
  1389. # "Canvas initialization finished in"), '%.2f' % self.used_time,
  1390. # _("Executing Tcl Script ...")),
  1391. # alignment=Qt.AlignBottom | Qt.AlignLeft,
  1392. # color=QtGui.QColor("gray"))
  1393. cmd_line_shellfile_text = myfile.read()
  1394. if self.cmd_line_headless != 1:
  1395. self.shell.exec_command(cmd_line_shellfile_text)
  1396. else:
  1397. self.shell.exec_command(cmd_line_shellfile_text, no_echo=True)
  1398. except Exception as ext:
  1399. print("ERROR: ", ext)
  1400. sys.exit(2)
  1401. # accept some type file as command line parameter: FlatCAM project, FlatCAM preferences or scripts
  1402. # the path/file_name must be enclosed in quotes if it contain spaces
  1403. if App.args:
  1404. self.args_at_startup.emit(App.args)
  1405. if self.defaults.old_defaults_found is True:
  1406. self.inform.emit('[WARNING_NOTCL] %s' % _("Found old default preferences files. "
  1407. "Please reboot the application to update."))
  1408. self.defaults.old_defaults_found = False
  1409. # ######################################### INIT FINISHED #######################################################
  1410. # #################################################################################################################
  1411. # #################################################################################################################
  1412. # #################################################################################################################
  1413. # #################################################################################################################
  1414. # #################################################################################################################
  1415. @staticmethod
  1416. def copy_and_overwrite(from_path, to_path):
  1417. """
  1418. From here:
  1419. https://stackoverflow.com/questions/12683834/how-to-copy-directory-recursively-in-python-and-overwrite-all
  1420. :param from_path: source path
  1421. :param to_path: destination path
  1422. :return: None
  1423. """
  1424. if os.path.exists(to_path):
  1425. shutil.rmtree(to_path)
  1426. try:
  1427. shutil.copytree(from_path, to_path)
  1428. except FileNotFoundError:
  1429. from_new_path = os.path.dirname(os.path.realpath(__file__)) + '\\appGUI\\VisPyData\\data'
  1430. shutil.copytree(from_new_path, to_path)
  1431. def on_startup_args(self, args, silent=False):
  1432. """
  1433. This will process any arguments provided to the application at startup. Like trying to launch a file or project.
  1434. :param silent: when True it will not print messages on Tcl Shell and/or status bar
  1435. :param args: a list containing the application args at startup
  1436. :return: None
  1437. """
  1438. if args is not None:
  1439. args_to_process = args
  1440. else:
  1441. args_to_process = App.args
  1442. log.debug("Application was started with arguments: %s. Processing ..." % str(args_to_process))
  1443. for argument in args_to_process:
  1444. if '.FlatPrj'.lower() in argument.lower():
  1445. try:
  1446. project_name = str(argument)
  1447. if project_name == "":
  1448. if silent is False:
  1449. self.inform.emit(_("Cancelled."))
  1450. else:
  1451. # self.open_project(project_name)
  1452. run_from_arg = True
  1453. # self.worker_task.emit({'fcn': self.open_project,
  1454. # 'params': [project_name, run_from_arg]})
  1455. self.open_project(filename=project_name, run_from_arg=run_from_arg)
  1456. except Exception as e:
  1457. log.debug("Could not open FlatCAM project file as App parameter due: %s" % str(e))
  1458. elif '.FlatConfig'.lower() in argument.lower():
  1459. try:
  1460. file_name = str(argument)
  1461. if file_name == "":
  1462. if silent is False:
  1463. self.inform.emit(_("Open Config file failed."))
  1464. else:
  1465. run_from_arg = True
  1466. # self.worker_task.emit({'fcn': self.open_config_file,
  1467. # 'params': [file_name, run_from_arg]})
  1468. self.open_config_file(file_name, run_from_arg=run_from_arg)
  1469. except Exception as e:
  1470. log.debug("Could not open FlatCAM Config file as App parameter due: %s" % str(e))
  1471. elif '.FlatScript'.lower() in argument.lower() or '.TCL'.lower() in argument.lower():
  1472. try:
  1473. file_name = str(argument)
  1474. if file_name == "":
  1475. if silent is False:
  1476. self.inform.emit(_("Open Script file failed."))
  1477. else:
  1478. if silent is False:
  1479. self.on_fileopenscript(name=file_name)
  1480. self.ui.plot_tab_area.setCurrentWidget(self.ui.plot_tab)
  1481. self.on_filerunscript(name=file_name)
  1482. except Exception as e:
  1483. log.debug("Could not open FlatCAM Script file as App parameter due: %s" % str(e))
  1484. elif 'quit'.lower() in argument.lower() or 'exit'.lower() in argument.lower():
  1485. log.debug("App.on_startup_args() --> Quit event.")
  1486. sys.exit()
  1487. elif 'save'.lower() in argument.lower():
  1488. log.debug("App.on_startup_args() --> Save event. App Defaults saved.")
  1489. self.preferencesUiManager.save_defaults()
  1490. else:
  1491. exc_list = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().split(',')
  1492. proc_arg = argument.lower()
  1493. for ext in exc_list:
  1494. proc_ext = ext.replace(' ', '')
  1495. proc_ext = '.%s' % proc_ext
  1496. if proc_ext.lower() in proc_arg and proc_ext != '.':
  1497. file_name = str(argument)
  1498. if file_name == "":
  1499. if silent is False:
  1500. self.inform.emit(_("Open Excellon file failed."))
  1501. else:
  1502. self.on_fileopenexcellon(name=file_name, signal=None)
  1503. return
  1504. gco_list = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().split(',')
  1505. for ext in gco_list:
  1506. proc_ext = ext.replace(' ', '')
  1507. proc_ext = '.%s' % proc_ext
  1508. if proc_ext.lower() in proc_arg and proc_ext != '.':
  1509. file_name = str(argument)
  1510. if file_name == "":
  1511. if silent is False:
  1512. self.inform.emit(_("Open GCode file failed."))
  1513. else:
  1514. self.on_fileopengcode(name=file_name, signal=None)
  1515. return
  1516. grb_list = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().split(',')
  1517. for ext in grb_list:
  1518. proc_ext = ext.replace(' ', '')
  1519. proc_ext = '.%s' % proc_ext
  1520. if proc_ext.lower() in proc_arg and proc_ext != '.':
  1521. file_name = str(argument)
  1522. if file_name == "":
  1523. if silent is False:
  1524. self.inform.emit(_("Open Gerber file failed."))
  1525. else:
  1526. self.on_fileopengerber(name=file_name, signal=None)
  1527. return
  1528. # if it reached here without already returning then the app was registered with a file that it does not
  1529. # recognize therefore we must quit but take into consideration the app reboot from within, in that case
  1530. # the args_to_process will contain the path to the FlatCAM.exe (cx_freezed executable)
  1531. # for arg in args_to_process:
  1532. # if 'FlatCAM.exe' in arg:
  1533. # continue
  1534. # else:
  1535. # sys.exit(2)
  1536. def set_ui_title(self, name):
  1537. """
  1538. Sets the title of the main window.
  1539. :param name: String that store the project path and project name
  1540. :return: None
  1541. """
  1542. self.ui.setWindowTitle('FlatCAM %s %s - %s - [%s] %s' %
  1543. (self.version,
  1544. ('BETA' if self.beta else ''),
  1545. platform.architecture()[0],
  1546. self.engine,
  1547. name)
  1548. )
  1549. def on_app_restart(self):
  1550. # make sure that the Sys Tray icon is hidden before restart otherwise it will
  1551. # be left in the SySTray
  1552. try:
  1553. self.trayIcon.hide()
  1554. except Exception:
  1555. pass
  1556. fcTranslate.restart_program(app=self)
  1557. def clear_pool(self):
  1558. """
  1559. Clear the multiprocessing pool and calls garbage collector.
  1560. :return: None
  1561. """
  1562. self.pool.close()
  1563. self.pool = Pool()
  1564. self.pool_recreated.emit(self.pool)
  1565. gc.collect()
  1566. def install_tools(self):
  1567. """
  1568. This installs the FlatCAM tools (plugin-like) which reside in their own classes.
  1569. Instantiation of the Tools classes.
  1570. The order that the tools are installed is important as they can depend on each other install position.
  1571. :return: None
  1572. """
  1573. # shell tool has t obe initialized always first because other tools print messages in the Shell Dock
  1574. self.shell = FCShell(app=self, version=self.version)
  1575. self.distance_tool = Distance(self)
  1576. self.distance_tool.install(icon=QtGui.QIcon(self.resource_location + '/distance16.png'), pos=self.ui.menuedit,
  1577. before=self.ui.menueditorigin,
  1578. separator=False)
  1579. self.distance_min_tool = DistanceMin(self)
  1580. self.distance_min_tool.install(icon=QtGui.QIcon(self.resource_location + '/distance_min16.png'),
  1581. pos=self.ui.menuedit,
  1582. before=self.ui.menueditorigin,
  1583. separator=True)
  1584. self.dblsidedtool = DblSidedTool(self)
  1585. self.dblsidedtool.install(icon=QtGui.QIcon(self.resource_location + '/doubleside16.png'), separator=False)
  1586. self.cal_exc_tool = ToolCalibration(self)
  1587. self.cal_exc_tool.install(icon=QtGui.QIcon(self.resource_location + '/calibrate_16.png'), pos=self.ui.menutool,
  1588. before=self.dblsidedtool.menuAction,
  1589. separator=False)
  1590. self.align_objects_tool = AlignObjects(self)
  1591. self.align_objects_tool.install(icon=QtGui.QIcon(self.resource_location + '/align16.png'), separator=False)
  1592. self.edrills_tool = ToolExtractDrills(self)
  1593. self.edrills_tool.install(icon=QtGui.QIcon(self.resource_location + '/drill16.png'), separator=True)
  1594. self.panelize_tool = Panelize(self)
  1595. self.panelize_tool.install(icon=QtGui.QIcon(self.resource_location + '/panelize16.png'))
  1596. self.film_tool = Film(self)
  1597. self.film_tool.install(icon=QtGui.QIcon(self.resource_location + '/film16.png'))
  1598. self.paste_tool = SolderPaste(self)
  1599. self.paste_tool.install(icon=QtGui.QIcon(self.resource_location + '/solderpastebis32.png'))
  1600. self.calculator_tool = ToolCalculator(self)
  1601. self.calculator_tool.install(icon=QtGui.QIcon(self.resource_location + '/calculator16.png'), separator=True)
  1602. self.sub_tool = ToolSub(self)
  1603. self.sub_tool.install(icon=QtGui.QIcon(self.resource_location + '/sub32.png'),
  1604. pos=self.ui.menutool, separator=True)
  1605. self.rules_tool = RulesCheck(self)
  1606. self.rules_tool.install(icon=QtGui.QIcon(self.resource_location + '/rules32.png'),
  1607. pos=self.ui.menutool, separator=False)
  1608. self.optimal_tool = ToolOptimal(self)
  1609. self.optimal_tool.install(icon=QtGui.QIcon(self.resource_location + '/open_excellon32.png'),
  1610. pos=self.ui.menutool, separator=True)
  1611. self.move_tool = ToolMove(self)
  1612. self.move_tool.install(icon=QtGui.QIcon(self.resource_location + '/move16.png'), pos=self.ui.menuedit,
  1613. before=self.ui.menueditorigin, separator=True)
  1614. self.cutout_tool = CutOut(self)
  1615. self.cutout_tool.install(icon=QtGui.QIcon(self.resource_location + '/cut16_bis.png'), pos=self.ui.menutool,
  1616. before=self.sub_tool.menuAction)
  1617. self.ncclear_tool = NonCopperClear(self)
  1618. self.ncclear_tool.install(icon=QtGui.QIcon(self.resource_location + '/ncc16.png'), pos=self.ui.menutool,
  1619. before=self.sub_tool.menuAction, separator=True)
  1620. self.paint_tool = ToolPaint(self)
  1621. self.paint_tool.install(icon=QtGui.QIcon(self.resource_location + '/paint16.png'), pos=self.ui.menutool,
  1622. before=self.sub_tool.menuAction, separator=True)
  1623. self.isolation_tool = ToolIsolation(self)
  1624. self.isolation_tool.install(icon=QtGui.QIcon(self.resource_location + '/iso_16.png'), pos=self.ui.menutool,
  1625. before=self.sub_tool.menuAction, separator=True)
  1626. self.drilling_tool = ToolDrilling(self)
  1627. self.drilling_tool.install(icon=QtGui.QIcon(self.resource_location + '/drill16.png'), pos=self.ui.menutool,
  1628. before=self.sub_tool.menuAction, separator=True)
  1629. self.copper_thieving_tool = ToolCopperThieving(self)
  1630. self.copper_thieving_tool.install(icon=QtGui.QIcon(self.resource_location + '/copperfill32.png'),
  1631. pos=self.ui.menutool)
  1632. self.fiducial_tool = ToolFiducials(self)
  1633. self.fiducial_tool.install(icon=QtGui.QIcon(self.resource_location + '/fiducials_32.png'),
  1634. pos=self.ui.menutool)
  1635. self.qrcode_tool = QRCode(self)
  1636. self.qrcode_tool.install(icon=QtGui.QIcon(self.resource_location + '/qrcode32.png'),
  1637. pos=self.ui.menutool)
  1638. self.punch_tool = ToolPunchGerber(self)
  1639. self.punch_tool.install(icon=QtGui.QIcon(self.resource_location + '/punch32.png'), pos=self.ui.menutool)
  1640. self.invert_tool = ToolInvertGerber(self)
  1641. self.invert_tool.install(icon=QtGui.QIcon(self.resource_location + '/invert32.png'), pos=self.ui.menutool)
  1642. self.corners_tool = ToolCorners(self)
  1643. self.corners_tool.install(icon=QtGui.QIcon(self.resource_location + '/corners_32.png'), pos=self.ui.menutool)
  1644. self.etch_tool = ToolEtchCompensation(self)
  1645. self.etch_tool.install(icon=QtGui.QIcon(self.resource_location + '/etch_32.png'), pos=self.ui.menutool)
  1646. self.transform_tool = ToolTransform(self)
  1647. self.transform_tool.install(icon=QtGui.QIcon(self.resource_location + '/transform.png'),
  1648. pos=self.ui.menuoptions, separator=True)
  1649. self.properties_tool = Properties(self)
  1650. self.properties_tool.install(icon=QtGui.QIcon(self.resource_location + '/properties32.png'),
  1651. pos=self.ui.menuoptions)
  1652. self.pdf_tool = ToolPDF(self)
  1653. self.pdf_tool.install(icon=QtGui.QIcon(self.resource_location + '/pdf32.png'),
  1654. pos=self.ui.menufileimport,
  1655. separator=True)
  1656. self.image_tool = ToolImage(self)
  1657. self.image_tool.install(icon=QtGui.QIcon(self.resource_location + '/image32.png'),
  1658. pos=self.ui.menufileimport,
  1659. separator=True)
  1660. self.pcb_wizard_tool = PcbWizard(self)
  1661. self.pcb_wizard_tool.install(icon=QtGui.QIcon(self.resource_location + '/drill32.png'),
  1662. pos=self.ui.menufileimport)
  1663. self.log.debug("Tools are installed.")
  1664. def remove_tools(self):
  1665. """
  1666. Will remove all the actions in the Tool menu.
  1667. :return: None
  1668. """
  1669. for act in self.ui.menutool.actions():
  1670. self.ui.menutool.removeAction(act)
  1671. def init_tools(self):
  1672. """
  1673. Initialize the Tool tab in the notebook side of the central widget.
  1674. Remove the actions in the Tools menu.
  1675. Instantiate again the FlatCAM tools (plugins).
  1676. All this is required when changing the layout: standard, compact etc.
  1677. :return: None
  1678. """
  1679. log.debug("init_tools()")
  1680. # delete the data currently in the Tools Tab and the Tab itself
  1681. widget = QtWidgets.QTabWidget.widget(self.ui.notebook, 2)
  1682. if widget is not None:
  1683. widget.deleteLater()
  1684. self.ui.notebook.removeTab(2)
  1685. # rebuild the Tools Tab
  1686. self.ui.tool_tab = QtWidgets.QWidget()
  1687. self.ui.tool_tab_layout = QtWidgets.QVBoxLayout(self.ui.tool_tab)
  1688. self.ui.tool_tab_layout.setContentsMargins(2, 2, 2, 2)
  1689. self.ui.notebook.addTab(self.ui.tool_tab, _("Tool"))
  1690. self.ui.tool_scroll_area = VerticalScrollArea()
  1691. self.ui.tool_tab_layout.addWidget(self.ui.tool_scroll_area)
  1692. # reinstall all the Tools as some may have been removed when the data was removed from the Tools Tab
  1693. # first remove all of them
  1694. self.remove_tools()
  1695. # re-add the TCL Shell action to the Tools menu and reconnect it to ist slot function
  1696. self.ui.menutoolshell = self.ui.menutool.addAction(QtGui.QIcon(self.resource_location + '/shell16.png'),
  1697. '&Command Line\tS')
  1698. self.ui.menutoolshell.triggered.connect(self.ui.toggle_shell_ui)
  1699. # third install all of them
  1700. try:
  1701. self.install_tools()
  1702. except AttributeError:
  1703. pass
  1704. self.log.debug("Tools are initialized.")
  1705. # def parse_system_fonts(self):
  1706. # self.worker_task.emit({'fcn': self.f_parse.get_fonts_by_types,
  1707. # 'params': []})
  1708. def connect_tools_signals_to_toolbar(self, ui):
  1709. ui.dblsided_btn.triggered.connect(lambda: self.dblsidedtool.run(toggle=True))
  1710. ui.cal_btn.triggered.connect(lambda: self.cal_exc_tool.run(toggle=True))
  1711. ui.align_btn.triggered.connect(lambda: self.align_objects_tool.run(toggle=True))
  1712. ui.extract_btn.triggered.connect(lambda: self.edrills_tool.run(toggle=True))
  1713. ui.cutout_btn.triggered.connect(lambda: self.cutout_tool.run(toggle=True))
  1714. ui.ncc_btn.triggered.connect(lambda: self.ncclear_tool.run(toggle=True))
  1715. ui.paint_btn.triggered.connect(lambda: self.paint_tool.run(toggle=True))
  1716. ui.isolation_btn.triggered.connect(lambda: self.isolation_tool.run(toggle=True))
  1717. ui.drill_btn.triggered.connect(lambda: self.drilling_tool.run(toggle=True))
  1718. ui.panelize_btn.triggered.connect(lambda: self.panelize_tool.run(toggle=True))
  1719. ui.film_btn.triggered.connect(lambda: self.film_tool.run(toggle=True))
  1720. ui.solder_btn.triggered.connect(lambda: self.paste_tool.run(toggle=True))
  1721. ui.sub_btn.triggered.connect(lambda: self.sub_tool.run(toggle=True))
  1722. ui.rules_btn.triggered.connect(lambda: self.rules_tool.run(toggle=True))
  1723. ui.optimal_btn.triggered.connect(lambda: self.optimal_tool.run(toggle=True))
  1724. ui.calculators_btn.triggered.connect(lambda: self.calculator_tool.run(toggle=True))
  1725. ui.transform_btn.triggered.connect(lambda: self.transform_tool.run(toggle=True))
  1726. ui.qrcode_btn.triggered.connect(lambda: self.qrcode_tool.run(toggle=True))
  1727. ui.copperfill_btn.triggered.connect(lambda: self.copper_thieving_tool.run(toggle=True))
  1728. ui.fiducials_btn.triggered.connect(lambda: self.fiducial_tool.run(toggle=True))
  1729. ui.punch_btn.triggered.connect(lambda: self.punch_tool.run(toggle=True))
  1730. ui.invert_btn.triggered.connect(lambda: self.invert_tool.run(toggle=True))
  1731. ui.corners_tool_btn.triggered.connect(lambda: self.corners_tool.run(toggle=True))
  1732. ui.etch_btn.triggered.connect(lambda: self.etch_tool.run(toggle=True))
  1733. def connect_toolbar_signals(self, ui):
  1734. """
  1735. Reconnect the signals to the actions in the toolbar.
  1736. This has to be done each time after the FlatCAM tools are removed/installed.
  1737. :return: None
  1738. """
  1739. # Toolbar
  1740. # File Toolbar Signals
  1741. # ui.file_new_btn.triggered.connect(self.on_file_new)
  1742. ui.file_open_btn.triggered.connect(self.f_handlers.on_file_openproject)
  1743. ui.file_save_btn.triggered.connect(self.f_handlers.on_file_saveproject)
  1744. ui.file_open_gerber_btn.triggered.connect(self.f_handlers.on_fileopengerber)
  1745. ui.file_open_excellon_btn.triggered.connect(self.f_handlers.on_fileopenexcellon)
  1746. # View Toolbar Signals
  1747. ui.clear_plot_btn.triggered.connect(self.clear_plots)
  1748. ui.replot_btn.triggered.connect(self.plot_all)
  1749. ui.zoom_fit_btn.triggered.connect(self.on_zoom_fit)
  1750. ui.zoom_in_btn.triggered.connect(lambda: self.plotcanvas.zoom(1 / 1.5))
  1751. ui.zoom_out_btn.triggered.connect(lambda: self.plotcanvas.zoom(1.5))
  1752. # Edit Toolbar Signals
  1753. ui.editgeo_btn.triggered.connect(self.object2editor)
  1754. ui.update_obj_btn.triggered.connect(lambda: self.editor2object())
  1755. ui.copy_btn.triggered.connect(self.on_copy_command)
  1756. ui.delete_btn.triggered.connect(self.on_delete)
  1757. ui.distance_btn.triggered.connect(lambda: self.distance_tool.run(toggle=True))
  1758. ui.distance_min_btn.triggered.connect(lambda: self.distance_min_tool.run(toggle=True))
  1759. ui.origin_btn.triggered.connect(self.on_set_origin)
  1760. ui.move2origin_btn.triggered.connect(self.on_move2origin)
  1761. ui.jmp_btn.triggered.connect(self.on_jump_to)
  1762. ui.locate_btn.triggered.connect(lambda: self.on_locate(obj=self.collection.get_active()))
  1763. # Scripting Toolbar Signals
  1764. ui.shell_btn.triggered.connect(ui.toggle_shell_ui)
  1765. ui.new_script_btn.triggered.connect(self.f_handlers.on_filenewscript)
  1766. ui.open_script_btn.triggered.connect(self.f_handlers.on_fileopenscript)
  1767. ui.run_script_btn.triggered.connect(self.f_handlers.on_filerunscript)
  1768. # Tools Toolbar Signals
  1769. try:
  1770. self.connect_tools_signals_to_toolbar(ui=ui)
  1771. except Exception as err:
  1772. log.debug("App.connect_toolbar_signals() tools signals -> %s" % str(err))
  1773. def object2editor(self):
  1774. """
  1775. Send the current Geometry, Gerber, Excellon object or CNCJob (if any) into the it's editor.
  1776. :return: None
  1777. """
  1778. self.defaults.report_usage("object2editor()")
  1779. # disable the objects menu as it may interfere with the appEditors
  1780. self.ui.menuobjects.setDisabled(True)
  1781. edited_object = self.collection.get_active()
  1782. if isinstance(edited_object, GerberObject) or isinstance(edited_object, GeometryObject) or \
  1783. isinstance(edited_object, ExcellonObject) or isinstance(edited_object, CNCJobObject):
  1784. pass
  1785. else:
  1786. self.inform.emit('[WARNING_NOTCL] %s' % _("Select a Geometry, Gerber, Excellon or CNCJob Object to edit."))
  1787. return
  1788. if isinstance(edited_object, GeometryObject):
  1789. # store the Geometry Editor Toolbar visibility before entering in the Editor
  1790. self.geo_editor.toolbar_old_state = True if self.ui.geo_edit_toolbar.isVisible() else False
  1791. # we set the notebook to hidden
  1792. # self.ui.splitter.setSizes([0, 1])
  1793. if edited_object.multigeo is True:
  1794. sel_rows = [item.row() for item in edited_object.ui.geo_tools_table.selectedItems()]
  1795. if len(sel_rows) > 1:
  1796. self.inform.emit('[WARNING_NOTCL] %s' %
  1797. _("Simultaneous editing of tools geometry in a MultiGeo Geometry "
  1798. "is not possible.\n"
  1799. "Edit only one geometry at a time."))
  1800. if not sel_rows:
  1801. self.inform.emit('[WARNING_NOTCL] %s.' % _("No Tool Selected"))
  1802. return
  1803. # determine the tool dia of the selected tool
  1804. selected_tooldia = float(edited_object.ui.geo_tools_table.item(sel_rows[0], 1).text())
  1805. # now find the key in the edited_object.tools that has this tooldia
  1806. multi_tool = 1
  1807. for tool in edited_object.tools:
  1808. if edited_object.tools[tool]['tooldia'] == selected_tooldia:
  1809. multi_tool = tool
  1810. break
  1811. log.debug("Editing MultiGeo Geometry with tool diameter: %s" % str(multi_tool))
  1812. self.geo_editor.edit_fcgeometry(edited_object, multigeo_tool=multi_tool)
  1813. else:
  1814. log.debug("Editing SingleGeo Geometry with tool diameter.")
  1815. self.geo_editor.edit_fcgeometry(edited_object)
  1816. # set call source to the Editor we go into
  1817. self.call_source = 'geo_editor'
  1818. elif isinstance(edited_object, ExcellonObject):
  1819. # store the Excellon Editor Toolbar visibility before entering in the Editor
  1820. self.exc_editor.toolbar_old_state = True if self.ui.exc_edit_toolbar.isVisible() else False
  1821. if self.ui.splitter.sizes()[0] == 0:
  1822. self.ui.splitter.setSizes([1, 1])
  1823. self.exc_editor.edit_fcexcellon(edited_object)
  1824. # set call source to the Editor we go into
  1825. self.call_source = 'exc_editor'
  1826. elif isinstance(edited_object, GerberObject):
  1827. # store the Gerber Editor Toolbar visibility before entering in the Editor
  1828. self.grb_editor.toolbar_old_state = True if self.ui.grb_edit_toolbar.isVisible() else False
  1829. if self.ui.splitter.sizes()[0] == 0:
  1830. self.ui.splitter.setSizes([1, 1])
  1831. self.grb_editor.edit_fcgerber(edited_object)
  1832. # set call source to the Editor we go into
  1833. self.call_source = 'grb_editor'
  1834. # reset the following variables so the UI is built again after edit
  1835. edited_object.ui_build = False
  1836. elif isinstance(edited_object, CNCJobObject):
  1837. if self.ui.splitter.sizes()[0] == 0:
  1838. self.ui.splitter.setSizes([1, 1])
  1839. # set call source to the Editor we go into
  1840. self.call_source = 'gcode_editor'
  1841. self.gcode_editor.edit_fcgcode(edited_object)
  1842. # make sure that we can't select another object while in Editor Mode:
  1843. # self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.NoSelection)
  1844. self.ui.project_frame.setDisabled(True)
  1845. # delete any selection shape that might be active as they are not relevant in Editor
  1846. self.delete_selection_shape()
  1847. # hide the Tools Toolbar
  1848. tools_tb = self.ui.toolbartools
  1849. if tools_tb.isVisible():
  1850. self.old_state_of_tools_toolbar = True
  1851. tools_tb.hide()
  1852. else:
  1853. self.old_state_of_tools_toolbar = False
  1854. self.ui.plot_tab_area.setTabText(0, _("EDITOR Area"))
  1855. self.ui.plot_tab_area.protectTab(0)
  1856. self.inform.emit('[WARNING_NOTCL] %s' % _("Editor is activated ..."))
  1857. self.should_we_save = True
  1858. def editor2object(self, cleanup=None):
  1859. """
  1860. Transfers the Geometry or Excellon from it's editor to the current object.
  1861. :return: None
  1862. """
  1863. self.defaults.report_usage("editor2object()")
  1864. # re-enable the objects menu that was disabled on entry in Editor mode
  1865. self.ui.menuobjects.setDisabled(False)
  1866. # do not update a geometry or excellon object unless it comes out of an editor
  1867. if self.call_source != 'app':
  1868. edited_obj = self.collection.get_active()
  1869. if cleanup is None:
  1870. msgbox = QtWidgets.QMessageBox()
  1871. msgbox.setText(_("Do you want to save the edited object?"))
  1872. msgbox.setWindowTitle(_("Close Editor"))
  1873. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  1874. msgbox.setIcon(QtWidgets.QMessageBox.Question)
  1875. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  1876. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  1877. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  1878. msgbox.setDefaultButton(bt_yes)
  1879. msgbox.exec_()
  1880. response = msgbox.clickedButton()
  1881. if response == bt_yes:
  1882. # show the Tools Toolbar
  1883. tools_tb = self.ui.toolbartools
  1884. if self.old_state_of_tools_toolbar is True:
  1885. tools_tb.show()
  1886. # clean the Tools Tab
  1887. self.ui.tool_scroll_area.takeWidget()
  1888. self.ui.tool_scroll_area.setWidget(QtWidgets.QWidget())
  1889. self.ui.notebook.setTabText(2, _("Tool"))
  1890. if edited_obj.kind == 'geometry':
  1891. obj_type = "Geometry"
  1892. self.geo_editor.update_fcgeometry(edited_obj)
  1893. # self.geo_editor.update_options(edited_obj)
  1894. # restore GUI to the Selected TAB
  1895. # Remove anything else in the appGUI
  1896. self.ui.tool_scroll_area.takeWidget()
  1897. # update the geo object options so it is including the bounding box values
  1898. try:
  1899. xmin, ymin, xmax, ymax = edited_obj.bounds(flatten=True)
  1900. edited_obj.options['xmin'] = xmin
  1901. edited_obj.options['ymin'] = ymin
  1902. edited_obj.options['xmax'] = xmax
  1903. edited_obj.options['ymax'] = ymax
  1904. except AttributeError as e:
  1905. self.inform.emit('[WARNING] %s' % _("Object empty after edit."))
  1906. log.debug("App.editor2object() --> Geometry --> %s" % str(e))
  1907. edited_obj.build_ui()
  1908. edited_obj.plot()
  1909. self.inform.emit('[success] %s' % _("Editor exited. Editor content saved."))
  1910. elif edited_obj.kind == 'gerber':
  1911. obj_type = "Gerber"
  1912. self.grb_editor.update_fcgerber()
  1913. # self.grb_editor.update_options(edited_obj)
  1914. # delete the old object (the source object) if it was an empty one
  1915. try:
  1916. if len(edited_obj.solid_geometry) == 0:
  1917. old_name = edited_obj.options['name']
  1918. self.collection.delete_by_name(old_name)
  1919. except TypeError:
  1920. # if the solid_geometry is a single Polygon the len() will not work
  1921. # in any case, falling here means that we have something in the solid_geometry, even if only
  1922. # a single Polygon, therefore we pass this
  1923. pass
  1924. self.inform.emit('[success] %s' % _("Editor exited. Editor content saved."))
  1925. # restore GUI to the Selected TAB
  1926. # Remove anything else in the GUI
  1927. self.ui.properties_scroll_area.takeWidget()
  1928. elif edited_obj.kind == 'excellon':
  1929. obj_type = "Excellon"
  1930. self.exc_editor.update_fcexcellon(edited_obj)
  1931. # self.exc_editor.update_options(edited_obj)
  1932. # restore GUI to the Selected TAB
  1933. # Remove anything else in the GUI
  1934. self.ui.tool_scroll_area.takeWidget()
  1935. # delete the old object (the source object) if it was an empty one
  1936. # find if we have drills:
  1937. has_drills = None
  1938. for tt in edited_obj.tools:
  1939. if 'drills' in edited_obj.tools[tt] and edited_obj.tools[tt]['drills']:
  1940. has_drills = True
  1941. break
  1942. # find if we have slots:
  1943. has_slots = None
  1944. for tt in edited_obj.tools:
  1945. if 'slots' in edited_obj.tools[tt] and edited_obj.tools[tt]['slots']:
  1946. has_slots = True
  1947. break
  1948. if has_drills is None and has_slots is None:
  1949. old_name = edited_obj.options['name']
  1950. self.collection.delete_by_name(name=old_name)
  1951. self.inform.emit('[success] %s' % _("Editor exited. Editor content saved."))
  1952. elif edited_obj.kind == 'cncjob':
  1953. obj_type = "CNCJob"
  1954. self.gcode_editor.update_fcgcode(edited_obj)
  1955. # self.exc_editor.update_options(edited_obj)
  1956. # restore GUI to the Selected TAB
  1957. # Remove anything else in the GUI
  1958. self.ui.tool_scroll_area.takeWidget()
  1959. edited_obj.build_ui()
  1960. # close the open tab
  1961. for idx in range(self.ui.plot_tab_area.count()):
  1962. if self.ui.plot_tab_area.widget(idx).objectName() == 'gcode_editor_tab':
  1963. self.ui.plot_tab_area.closeTab(idx)
  1964. self.inform.emit('[success] %s' % _("Editor exited. Editor content saved."))
  1965. else:
  1966. self.inform.emit('[WARNING_NOTCL] %s' %
  1967. _("Select a Gerber, Geometry, Excellon or CNCJob Object to update."))
  1968. return
  1969. self.inform.emit('[selected] %s %s' % (obj_type, _("is updated, returning to App...")))
  1970. elif response == bt_no:
  1971. # show the Tools Toolbar
  1972. tools_tb = self.ui.toolbartools
  1973. if self.old_state_of_tools_toolbar is True:
  1974. tools_tb.show()
  1975. # clean the Tools Tab
  1976. self.ui.tool_scroll_area.takeWidget()
  1977. self.ui.tool_scroll_area.setWidget(QtWidgets.QWidget())
  1978. self.ui.notebook.setTabText(2, _("Tool"))
  1979. self.inform.emit('[WARNING_NOTCL] %s' % _("Editor exited. Editor content was not saved."))
  1980. if edited_obj.kind == 'geometry':
  1981. self.geo_editor.deactivate()
  1982. edited_obj.build_ui()
  1983. edited_obj.plot()
  1984. elif edited_obj.kind == 'gerber':
  1985. self.grb_editor.deactivate_grb_editor()
  1986. edited_obj.build_ui()
  1987. elif edited_obj.kind == 'excellon':
  1988. self.exc_editor.deactivate()
  1989. edited_obj.build_ui()
  1990. elif edited_obj.kind == 'cncjob':
  1991. self.gcode_editor.deactivate()
  1992. edited_obj.build_ui()
  1993. # close the open tab
  1994. for idx in range(self.ui.plot_tab_area.count()):
  1995. try:
  1996. if self.ui.plot_tab_area.widget(idx).objectName() == 'gcode_editor_tab':
  1997. self.ui.plot_tab_area.closeTab(idx)
  1998. except AttributeError:
  1999. continue
  2000. else:
  2001. self.inform.emit('[WARNING_NOTCL] %s' %
  2002. _("Select a Gerber, Geometry, Excellon or CNCJob Object to update."))
  2003. return
  2004. elif response == bt_cancel:
  2005. return
  2006. # edited_obj.set_ui(edited_obj.ui_type(decimals=self.decimals))
  2007. # edited_obj.build_ui()
  2008. # Switch notebook to Properties page
  2009. # self.ui.notebook.setCurrentWidget(self.ui.properties_tab)
  2010. else:
  2011. # show the Tools Toolbar
  2012. tools_tb = self.ui.toolbartools
  2013. if self.old_state_of_tools_toolbar is True:
  2014. tools_tb.show()
  2015. if isinstance(edited_obj, GeometryObject):
  2016. self.geo_editor.deactivate()
  2017. elif isinstance(edited_obj, GerberObject):
  2018. self.grb_editor.deactivate_grb_editor()
  2019. elif isinstance(edited_obj, ExcellonObject):
  2020. self.exc_editor.deactivate()
  2021. else:
  2022. self.inform.emit('[WARNING_NOTCL] %s' %
  2023. _("Select a Gerber, Geometry or Excellon Object to update."))
  2024. return
  2025. # if notebook is hidden we show it
  2026. if self.ui.splitter.sizes()[0] == 0:
  2027. self.ui.splitter.setSizes([1, 1])
  2028. # restore the call_source to app
  2029. self.call_source = 'app'
  2030. # edited_obj.plot()
  2031. self.ui.plot_tab_area.setTabText(0, _("Plot Area"))
  2032. self.ui.plot_tab_area.protectTab(0)
  2033. # make sure that we reenable the selection on Project Tab after returning from Editor Mode:
  2034. # self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection)
  2035. self.ui.project_frame.setDisabled(False)
  2036. def get_last_folder(self):
  2037. """
  2038. Get the folder path from where the last file was opened.
  2039. :return: String, last opened folder path
  2040. """
  2041. return self.defaults["global_last_folder"]
  2042. def get_last_save_folder(self):
  2043. """
  2044. Get the folder path from where the last file was saved.
  2045. :return: String, last saved folder path
  2046. """
  2047. loc = self.defaults["global_last_save_folder"]
  2048. if loc is None:
  2049. loc = self.defaults["global_last_folder"]
  2050. if loc is None:
  2051. loc = os.path.dirname(__file__)
  2052. return loc
  2053. @QtCore.pyqtSlot(str)
  2054. @QtCore.pyqtSlot(str, bool)
  2055. def info(self, msg, shell_echo=True):
  2056. """
  2057. Informs the user. Normally on the status bar, optionally
  2058. also on the shell.
  2059. :param msg: Text to write.
  2060. :type msg: str
  2061. :param shell_echo: Control if to display the message msg in the Shell
  2062. :type shell_echo: bool
  2063. :return: None
  2064. """
  2065. # Type of message in brackets at the beginning of the message.
  2066. match = re.search(r"\[(.*)\](.*)", msg)
  2067. if match:
  2068. level = match.group(1)
  2069. msg_ = match.group(2)
  2070. self.ui.fcinfo.set_status(str(msg_), level=level)
  2071. if shell_echo is True:
  2072. if level.lower() == "error":
  2073. self.shell_message(msg, error=True, show=True)
  2074. elif level.lower() == "warning":
  2075. self.shell_message(msg, warning=True, show=True)
  2076. elif level.lower() == "error_notcl":
  2077. self.shell_message(msg, error=True, show=False)
  2078. elif level.lower() == "warning_notcl":
  2079. self.shell_message(msg, warning=True, show=False)
  2080. elif level.lower() == "success":
  2081. self.shell_message(msg, success=True, show=False)
  2082. elif level.lower() == "selected":
  2083. self.shell_message(msg, selected=True, show=False)
  2084. else:
  2085. self.shell_message(msg, show=False)
  2086. else:
  2087. self.ui.fcinfo.set_status(str(msg), level="info")
  2088. # make sure that if the message is to clear the infobar with a space
  2089. # is not printed over and over on the shell
  2090. if msg != '' and shell_echo is True:
  2091. self.shell_message(msg)
  2092. def info_shell(self, msg, new_line=True):
  2093. self.shell_message(msg=msg, new_line=new_line)
  2094. def save_to_file(self, content_to_save, txt_content):
  2095. """
  2096. Save something to a file.
  2097. :return: None
  2098. """
  2099. self.defaults.report_usage("save_to_file")
  2100. App.log.debug("save_to_file()")
  2101. self.date = str(datetime.today()).rpartition('.')[0]
  2102. self.date = ''.join(c for c in self.date if c not in ':-')
  2103. self.date = self.date.replace(' ', '_')
  2104. filter__ = "HTML File .html (*.html);;TXT File .txt (*.txt);;All Files (*.*)"
  2105. path_to_save = self.defaults["global_last_save_folder"] if \
  2106. self.defaults["global_last_save_folder"] is not None else self.data_path
  2107. try:
  2108. filename, _f = FCFileSaveDialog.get_saved_filename(
  2109. caption=_("Save to file"),
  2110. directory=path_to_save + '/file_' + self.date,
  2111. ext_filter=filter__
  2112. )
  2113. except TypeError:
  2114. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save to file"), ext_filter=filter__)
  2115. filename = str(filename)
  2116. if filename == "":
  2117. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  2118. return
  2119. else:
  2120. try:
  2121. with open(filename, 'w') as f:
  2122. ___ = f.read()
  2123. except PermissionError:
  2124. self.inform.emit('[WARNING] %s' %
  2125. _("Permission denied, saving not possible.\n"
  2126. "Most likely another app is holding the file open and not accessible."))
  2127. return
  2128. except IOError:
  2129. App.log.debug('Creating a new file ...')
  2130. f = open(filename, 'w')
  2131. f.close()
  2132. except Exception:
  2133. e = sys.exc_info()[0]
  2134. App.log.error("Could not load the file.")
  2135. App.log.error(str(e))
  2136. self.inform.emit('[ERROR_NOTCL] %s' % _("Could not load the file."))
  2137. return
  2138. # Save content
  2139. if filename.rpartition('.')[2].lower() == 'html':
  2140. file_content = content_to_save
  2141. else:
  2142. file_content = txt_content
  2143. try:
  2144. with open(filename, "w") as f:
  2145. f.write(file_content)
  2146. except Exception:
  2147. self.inform.emit('[ERROR_NOTCL] %s %s' % (_("Failed to write defaults to file."), str(filename)))
  2148. return
  2149. self.inform.emit('[success] %s: %s' % (_("Exported file to"), filename))
  2150. def register_recent(self, kind, filename):
  2151. """
  2152. Will register the files opened into record dictionaries. The FlatCAM projects has it's own
  2153. dictionary.
  2154. :param kind: type of file that was opened
  2155. :param filename: the path and file name for the file that was opened
  2156. :return:
  2157. """
  2158. self.log.debug("register_recent()")
  2159. self.log.debug(" %s" % kind)
  2160. self.log.debug(" %s" % filename)
  2161. record = {'kind': str(kind), 'filename': str(filename)}
  2162. if record in self.recent:
  2163. return
  2164. if record in self.recent_projects:
  2165. return
  2166. if record['kind'] == 'project':
  2167. self.recent_projects.insert(0, record)
  2168. else:
  2169. self.recent.insert(0, record)
  2170. if len(self.recent) > self.defaults['global_recent_limit']: # Limit reached
  2171. self.recent.pop()
  2172. if len(self.recent_projects) > self.defaults['global_recent_limit']: # Limit reached
  2173. self.recent_projects.pop()
  2174. try:
  2175. f = open(self.data_path + '/recent.json', 'w')
  2176. except IOError:
  2177. App.log.error("Failed to open recent items file for writing.")
  2178. self.inform.emit('[ERROR_NOTCL] %s' %
  2179. _('Failed to open recent files file for writing.'))
  2180. return
  2181. json.dump(self.recent, f, default=to_dict, indent=2, sort_keys=True)
  2182. f.close()
  2183. try:
  2184. fp = open(self.data_path + '/recent_projects.json', 'w')
  2185. except IOError:
  2186. App.log.error("Failed to open recent items file for writing.")
  2187. self.inform.emit('[ERROR_NOTCL] %s' %
  2188. _('Failed to open recent projects file for writing.'))
  2189. return
  2190. json.dump(self.recent_projects, fp, default=to_dict, indent=2, sort_keys=True)
  2191. fp.close()
  2192. # Re-build the recent items menu
  2193. self.setup_recent_items()
  2194. def on_about(self):
  2195. """
  2196. Displays the "about" dialog found in the Menu --> Help.
  2197. :return: None
  2198. """
  2199. self.defaults.report_usage("on_about")
  2200. version = self.version
  2201. version_date = self.version_date
  2202. beta = self.beta
  2203. class AboutDialog(QtWidgets.QDialog):
  2204. def __init__(self, app, parent=None):
  2205. QtWidgets.QDialog.__init__(self, parent)
  2206. self.app = app
  2207. # Icon and title
  2208. self.setWindowIcon(parent.app_icon)
  2209. self.setWindowTitle(_("About FlatCAM"))
  2210. self.resize(600, 200)
  2211. # self.setStyleSheet("background-image: url(share/flatcam_icon256.png); background-attachment: fixed")
  2212. # self.setStyleSheet(
  2213. # "border-image: url(share/flatcam_icon256.png) 0 0 0 0 stretch stretch; "
  2214. # "background-attachment: fixed"
  2215. # )
  2216. # bgimage = QtGui.QImage(self.resource_location + '/flatcam_icon256.png')
  2217. # s_bgimage = bgimage.scaled(QtCore.QSize(self.frameGeometry().width(), self.frameGeometry().height()))
  2218. # palette = QtGui.QPalette()
  2219. # palette.setBrush(10, QtGui.QBrush(bgimage)) # 10 = Windowrole
  2220. # self.setPalette(palette)
  2221. logo = QtWidgets.QLabel()
  2222. logo.setPixmap(QtGui.QPixmap(self.app.resource_location + '/flatcam_icon256.png'))
  2223. title = QtWidgets.QLabel(
  2224. "<font size=8><B>FlatCAM</B></font><BR>"
  2225. "{title}<BR>"
  2226. "<BR>"
  2227. "<BR>"
  2228. "<a href = \"https://bitbucket.org/jpcgt/flatcam/src/Beta/\"><B>{devel}</B></a><BR>"
  2229. "<a href = \"https://bitbucket.org/jpcgt/flatcam/downloads/\"><b>{down}</B></a><BR>"
  2230. "<a href = \"https://bitbucket.org/jpcgt/flatcam/issues?status=new&status=open/\">"
  2231. "<B>{issue}</B></a><BR>".format(
  2232. title=_("2D Computer-Aided Printed Circuit Board Manufacturing"),
  2233. devel=_("Development"),
  2234. down=_("DOWNLOAD"),
  2235. issue=_("Issue tracker"))
  2236. )
  2237. title.setOpenExternalLinks(True)
  2238. closebtn = QtWidgets.QPushButton(_("Close"))
  2239. tab_widget = QtWidgets.QTabWidget()
  2240. description_label = QtWidgets.QLabel(
  2241. "FlatCAM {version} {beta} ({date}) - {arch}<br>"
  2242. "<a href = \"http://flatcam.org/\">http://flatcam.org</a><br>".format(
  2243. version=version,
  2244. beta=('BETA' if beta else ''),
  2245. date=version_date,
  2246. arch=platform.architecture()[0])
  2247. )
  2248. description_label.setOpenExternalLinks(True)
  2249. lic_lbl_header = QtWidgets.QLabel(
  2250. '%s:<br>%s<br>' % (
  2251. _('Licensed under the MIT license'),
  2252. "<a href = \"http://www.opensource.org/licenses/mit-license.php\">"
  2253. "http://www.opensource.org/licenses/mit-license.php</a>"
  2254. )
  2255. )
  2256. lic_lbl_header.setOpenExternalLinks(True)
  2257. lic_lbl_body = QtWidgets.QLabel(
  2258. _(
  2259. 'Permission is hereby granted, free of charge, to any person obtaining a copy\n'
  2260. 'of this software and associated documentation files (the "Software"), to deal\n'
  2261. 'in the Software without restriction, including without limitation the rights\n'
  2262. 'to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n'
  2263. 'copies of the Software, and to permit persons to whom the Software is\n'
  2264. 'furnished to do so, subject to the following conditions:\n\n'
  2265. 'The above copyright notice and this permission notice shall be included in\n'
  2266. 'all copies or substantial portions of the Software.\n\n'
  2267. 'THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n'
  2268. 'IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n'
  2269. 'FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n'
  2270. 'AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n'
  2271. 'LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n'
  2272. 'OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n'
  2273. 'THE SOFTWARE.'
  2274. )
  2275. )
  2276. attributions_label = QtWidgets.QLabel(
  2277. _(
  2278. 'Some of the icons used are from the following sources:<br>'
  2279. '<div>Icons by <a href="https://www.flaticon.com/authors/freepik" '
  2280. 'title="Freepik">Freepik</a> from <a href="https://www.flaticon.com/" '
  2281. 'title="Flaticon">www.flaticon.com</a></div>'
  2282. '<div>Icons by <a target="_blank" href="https://icons8.com">Icons8</a></div>'
  2283. 'Icons by <a href="http://www.onlinewebfonts.com">oNline Web Fonts</a>'
  2284. '<div>Icons by <a href="https://www.flaticon.com/authors/pixel-perfect" '
  2285. 'title="Pixel perfect">Pixel perfect</a> from <a href="https://www.flaticon.com/" '
  2286. 'title="Flaticon">www.flaticon.com</a></div>'
  2287. )
  2288. )
  2289. attributions_label.setOpenExternalLinks(True)
  2290. # layouts
  2291. layout1 = QtWidgets.QVBoxLayout()
  2292. layout1_1 = QtWidgets.QHBoxLayout()
  2293. layout1_2 = QtWidgets.QHBoxLayout()
  2294. layout2 = QtWidgets.QHBoxLayout()
  2295. layout3 = QtWidgets.QHBoxLayout()
  2296. self.setLayout(layout1)
  2297. layout1.addLayout(layout1_1)
  2298. layout1.addLayout(layout1_2)
  2299. layout1.addLayout(layout2)
  2300. layout1.addLayout(layout3)
  2301. layout1_1.addStretch()
  2302. layout1_1.addWidget(description_label)
  2303. layout1_2.addWidget(tab_widget)
  2304. self.splash_tab = QtWidgets.QWidget()
  2305. self.splash_tab.setObjectName("splash_about")
  2306. self.splash_tab_layout = QtWidgets.QHBoxLayout(self.splash_tab)
  2307. self.splash_tab_layout.setContentsMargins(2, 2, 2, 2)
  2308. tab_widget.addTab(self.splash_tab, _("Splash"))
  2309. self.programmmers_tab = QtWidgets.QWidget()
  2310. self.programmmers_tab.setObjectName("programmers_about")
  2311. self.programmmers_tab_layout = QtWidgets.QVBoxLayout(self.programmmers_tab)
  2312. self.programmmers_tab_layout.setContentsMargins(2, 2, 2, 2)
  2313. tab_widget.addTab(self.programmmers_tab, _("Programmers"))
  2314. self.translators_tab = QtWidgets.QWidget()
  2315. self.translators_tab.setObjectName("translators_about")
  2316. self.translators_tab_layout = QtWidgets.QVBoxLayout(self.translators_tab)
  2317. self.translators_tab_layout.setContentsMargins(2, 2, 2, 2)
  2318. tab_widget.addTab(self.translators_tab, _("Translators"))
  2319. self.license_tab = QtWidgets.QWidget()
  2320. self.license_tab.setObjectName("license_about")
  2321. self.license_tab_layout = QtWidgets.QVBoxLayout(self.license_tab)
  2322. self.license_tab_layout.setContentsMargins(2, 2, 2, 2)
  2323. tab_widget.addTab(self.license_tab, _("License"))
  2324. self.attributions_tab = QtWidgets.QWidget()
  2325. self.attributions_tab.setObjectName("attributions_about")
  2326. self.attributions_tab_layout = QtWidgets.QVBoxLayout(self.attributions_tab)
  2327. self.attributions_tab_layout.setContentsMargins(2, 2, 2, 2)
  2328. tab_widget.addTab(self.attributions_tab, _("Attributions"))
  2329. self.splash_tab_layout.addWidget(logo, stretch=0)
  2330. self.splash_tab_layout.addWidget(title, stretch=1)
  2331. pal = QtGui.QPalette()
  2332. pal.setColor(QtGui.QPalette.Background, Qt.white)
  2333. self.prog_grid_lay = QtWidgets.QGridLayout()
  2334. self.prog_grid_lay.setHorizontalSpacing(20)
  2335. self.prog_grid_lay.setColumnStretch(0, 0)
  2336. self.prog_grid_lay.setColumnStretch(2, 1)
  2337. prog_widget = QtWidgets.QWidget()
  2338. prog_widget.setLayout(self.prog_grid_lay)
  2339. prog_scroll = QtWidgets.QScrollArea()
  2340. prog_scroll.setWidget(prog_widget)
  2341. prog_scroll.setWidgetResizable(True)
  2342. prog_scroll.setFrameShape(QtWidgets.QFrame.NoFrame)
  2343. prog_scroll.setPalette(pal)
  2344. self.programmmers_tab_layout.addWidget(prog_scroll)
  2345. self.prog_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Programmer")), 0, 0)
  2346. self.prog_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Status")), 0, 1)
  2347. self.prog_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("E-mail")), 0, 2)
  2348. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Juan Pablo Caram"), 1, 0)
  2349. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % _("Program Author")), 1, 1)
  2350. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<>"), 1, 2)
  2351. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Denis Hayrullin"), 2, 0)
  2352. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Kamil Sopko"), 3, 0)
  2353. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu"), 4, 0)
  2354. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % _("BETA Maintainer >= 2019")), 4, 1)
  2355. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<marius_adrian@yahoo.com>"), 4, 2)
  2356. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 5, 0)
  2357. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "David Robertson"), 6, 0)
  2358. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Matthieu Berthomé"), 7, 0)
  2359. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Mike Evans"), 8, 0)
  2360. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Victor Benso"), 9, 0)
  2361. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 10, 0)
  2362. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Jørn Sandvik Nilsson"), 12, 0)
  2363. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Lei Zheng"), 13, 0)
  2364. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Leandro Heck"), 14, 0)
  2365. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marco A Quezada"), 15, 0)
  2366. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 16, 0)
  2367. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Cedric Dussud"), 20, 0)
  2368. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Chris Hemingway"), 22, 0)
  2369. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Damian Wrobel"), 24, 0)
  2370. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Daniel Sallin"), 28, 0)
  2371. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 32, 0)
  2372. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Bruno Vunderl"), 40, 0)
  2373. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Gonzalo Lopez"), 42, 0)
  2374. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Jakob Staudt"), 45, 0)
  2375. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Mike Smith"), 49, 0)
  2376. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 52, 0)
  2377. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Barnaby Walters"), 55, 0)
  2378. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Steve Martina"), 57, 0)
  2379. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Thomas Duffin"), 59, 0)
  2380. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Andrey Kultyapov"), 61, 0)
  2381. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 63, 0)
  2382. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Alex Lazar"), 64, 0)
  2383. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Chris Breneman"), 65, 0)
  2384. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Eric Varsanyi"), 67, 0)
  2385. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Lubos Medovarsky"), 69, 0)
  2386. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 74, 0)
  2387. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@Idechix"), 100, 0)
  2388. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@SM"), 101, 0)
  2389. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@grbf"), 102, 0)
  2390. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@Symonty"), 103, 0)
  2391. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@mgix"), 104, 0)
  2392. self.translator_grid_lay = QtWidgets.QGridLayout()
  2393. self.translator_grid_lay.setColumnStretch(0, 0)
  2394. self.translator_grid_lay.setColumnStretch(1, 0)
  2395. self.translator_grid_lay.setColumnStretch(2, 1)
  2396. self.translator_grid_lay.setColumnStretch(3, 0)
  2397. # trans_widget = QtWidgets.QWidget()
  2398. # trans_widget.setLayout(self.translator_grid_lay)
  2399. # self.translators_tab_layout.addWidget(trans_widget)
  2400. # self.translators_tab_layout.addStretch()
  2401. trans_widget = QtWidgets.QWidget()
  2402. trans_widget.setLayout(self.translator_grid_lay)
  2403. trans_scroll = QtWidgets.QScrollArea()
  2404. trans_scroll.setWidget(trans_widget)
  2405. trans_scroll.setWidgetResizable(True)
  2406. trans_scroll.setFrameShape(QtWidgets.QFrame.NoFrame)
  2407. trans_scroll.setPalette(pal)
  2408. self.translators_tab_layout.addWidget(trans_scroll)
  2409. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Language")), 0, 0)
  2410. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Translator")), 0, 1)
  2411. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Corrections")), 0, 2)
  2412. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("E-mail")), 0, 3)
  2413. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "BR - Portuguese"), 1, 0)
  2414. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Carlos Stein"), 1, 1)
  2415. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<carlos.stein@gmail.com>"), 1, 3)
  2416. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "French"), 2, 0)
  2417. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Michel Maciejewski"), 2, 1)
  2418. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % ""), 2, 2)
  2419. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<micmac589@gmail.com>"), 2, 3)
  2420. # self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Hungarian"), 3, 0)
  2421. # self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 3, 1)
  2422. # self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 3, 2)
  2423. # self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 3, 3)
  2424. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Italian"), 4, 0)
  2425. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Massimiliano Golfetto"), 4, 1)
  2426. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 4, 2)
  2427. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<golfetto.pcb@gmail.com>"), 4, 3)
  2428. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "German"), 5, 0)
  2429. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu (Google-Tr)"), 5, 1)
  2430. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Jens Karstedt, Detlef Eckardt"), 5, 2)
  2431. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 5, 3)
  2432. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Romanian"), 6, 0)
  2433. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu"), 6, 1)
  2434. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<marius_adrian@yahoo.com>"), 6, 3)
  2435. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Russian"), 7, 0)
  2436. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Andrey Kultyapov"), 7, 1)
  2437. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<camellan@yandex.ru>"), 7, 3)
  2438. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Spanish"), 8, 0)
  2439. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu (Google-Tr)"), 8, 1)
  2440. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % ""), 8, 2)
  2441. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 8, 3)
  2442. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Turkish"), 9, 0)
  2443. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Mehmet Kaya"), 9, 1)
  2444. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<malatyakaya480@gmail.com>"), 9, 3)
  2445. self.translator_grid_lay.setColumnStretch(0, 0)
  2446. self.translators_tab_layout.addStretch()
  2447. self.license_tab_layout.addWidget(lic_lbl_header)
  2448. self.license_tab_layout.addWidget(lic_lbl_body)
  2449. self.license_tab_layout.addStretch()
  2450. self.attributions_tab_layout.addWidget(attributions_label)
  2451. self.attributions_tab_layout.addStretch()
  2452. layout3.addStretch()
  2453. layout3.addWidget(closebtn)
  2454. closebtn.clicked.connect(self.accept)
  2455. AboutDialog(app=self, parent=self.ui).exec_()
  2456. def on_readme(self):
  2457. """
  2458. Displays the "about" dialog found in the Menu --> Help.
  2459. :return: None
  2460. """
  2461. class ReadmeDialog(QtWidgets.QDialog):
  2462. def __init__(self, app, parent=None):
  2463. QtWidgets.QDialog.__init__(self, parent)
  2464. self.app = app
  2465. open_source_link = "<a href = 'https://opensource.org/'<b>Open Source</b></a>"
  2466. new_features_link = "<a href = 'https://bitbucket.org/jpcgt/flatcam/pull-requests/'" \
  2467. "<b>click</b></a>"
  2468. bugs_link = "<a href = 'https://bitbucket.org/jpcgt/flatcam/issues/new'<b>click</b></a>"
  2469. # donation_link = "<a href = 'https://www.paypal.com/cgi-bin/webscr?cmd=_" \
  2470. # "donations&business=WLTJJ3Q77D98L&currency_code=USD&source=url'<b>click</b></a>"
  2471. # Icon and title
  2472. self.setWindowIcon(parent.app_icon)
  2473. self.setWindowTitle(_("Important Information's"))
  2474. self.resize(750, 375)
  2475. logo = QtWidgets.QLabel()
  2476. logo.setPixmap(QtGui.QPixmap(self.app.resource_location + '/contribute256.png'))
  2477. # content = QtWidgets.QLabel(
  2478. # "%s<br>"
  2479. # "%s<br><br>"
  2480. # "%s,<br>"
  2481. # "%s<br>"
  2482. # "<ul>"
  2483. # "<li> &nbsp;%s %s</li>"
  2484. # "<li> &nbsp;%s %s</li>"
  2485. # "</ul>"
  2486. # "%s %s.<br>"
  2487. # "%s"
  2488. # "<ul>"
  2489. # "<li> &nbsp;%s &#128077;</li>"
  2490. # "<li> &nbsp;%s &#128513;</li>"
  2491. # "</ul>" %
  2492. # (
  2493. # _("This program is %s and free in a very wide meaning of the word.") % open_source_link,
  2494. # _("Yet it cannot evolve without <b>contributions</b>."),
  2495. # _("If you want to see this application grow and become better and better"),
  2496. # _("you can <b>contribute</b> to the development yourself by:"),
  2497. # _("Pull Requests on the Bitbucket repository, if you are a developer"),
  2498. # new_features_link,
  2499. # _("Bug Reports by providing the steps required to reproduce the bug"),
  2500. # bugs_link,
  2501. # _("If you like or use this program you can make a donation"),
  2502. # donation_link,
  2503. # _("You don't have to make a donation %s, and it is totally optional but:") % donation_link,
  2504. # _("it will be welcomed with joy"),
  2505. # _("it will give me a reason to continue")
  2506. # )
  2507. # )
  2508. content = QtWidgets.QLabel(
  2509. "%s<br>"
  2510. "%s<br><br>"
  2511. "%s,<br>"
  2512. "%s<br>"
  2513. "<ul>"
  2514. "<li> &nbsp;%s %s</li>"
  2515. "<li> &nbsp;%s %s</li>"
  2516. "</ul>" %
  2517. (
  2518. _("This program is %s and free in a very wide meaning of the word.") % open_source_link,
  2519. _("Yet it cannot evolve without <b>contributions</b>."),
  2520. _("If you want to see this application grow and become better and better"),
  2521. _("you can <b>contribute</b> to the development yourself by:"),
  2522. _("Pull Requests on the Bitbucket repository, if you are a developer"),
  2523. new_features_link,
  2524. _("Bug Reports by providing the steps required to reproduce the bug"),
  2525. bugs_link
  2526. )
  2527. )
  2528. content.setOpenExternalLinks(True)
  2529. # palette
  2530. pal = QtGui.QPalette()
  2531. pal.setColor(QtGui.QPalette.Background, Qt.white)
  2532. # layouts
  2533. main_layout = QtWidgets.QVBoxLayout()
  2534. self.setLayout(main_layout)
  2535. tab_layout = QtWidgets.QHBoxLayout()
  2536. buttons_hlay = QtWidgets.QHBoxLayout()
  2537. main_layout.addLayout(tab_layout)
  2538. main_layout.addLayout(buttons_hlay)
  2539. tab_widget = QtWidgets.QTabWidget()
  2540. tab_layout.addWidget(tab_widget)
  2541. closebtn = QtWidgets.QPushButton(_("Close"))
  2542. buttons_hlay.addStretch()
  2543. buttons_hlay.addWidget(closebtn)
  2544. # CONTRIBUTE section
  2545. self.intro_tab = QtWidgets.QWidget()
  2546. self.intro_tab_layout = QtWidgets.QHBoxLayout(self.intro_tab)
  2547. self.intro_tab_layout.setContentsMargins(2, 2, 2, 2)
  2548. tab_widget.addTab(self.intro_tab, _("Contribute"))
  2549. self.grid_lay = QtWidgets.QGridLayout()
  2550. self.grid_lay.setHorizontalSpacing(20)
  2551. self.grid_lay.setColumnStretch(0, 0)
  2552. self.grid_lay.setColumnStretch(1, 1)
  2553. intro_wdg = QtWidgets.QWidget()
  2554. intro_wdg.setLayout(self.grid_lay)
  2555. intro_scroll_area = QtWidgets.QScrollArea()
  2556. intro_scroll_area.setWidget(intro_wdg)
  2557. intro_scroll_area.setWidgetResizable(True)
  2558. intro_scroll_area.setFrameShape(QtWidgets.QFrame.NoFrame)
  2559. intro_scroll_area.setPalette(pal)
  2560. self.grid_lay.addWidget(logo, 0, 0)
  2561. self.grid_lay.addWidget(content, 0, 1)
  2562. self.intro_tab_layout.addWidget(intro_scroll_area)
  2563. # LINKS EXCHANGE section
  2564. self.links_tab = QtWidgets.QWidget()
  2565. self.links_tab_layout = QtWidgets.QVBoxLayout(self.links_tab)
  2566. self.links_tab_layout.setContentsMargins(2, 2, 2, 2)
  2567. tab_widget.addTab(self.links_tab, _("Links Exchange"))
  2568. self.links_lay = QtWidgets.QHBoxLayout()
  2569. links_wdg = QtWidgets.QWidget()
  2570. links_wdg.setLayout(self.links_lay)
  2571. links_scroll_area = QtWidgets.QScrollArea()
  2572. links_scroll_area.setWidget(links_wdg)
  2573. links_scroll_area.setWidgetResizable(True)
  2574. links_scroll_area.setFrameShape(QtWidgets.QFrame.NoFrame)
  2575. links_scroll_area.setPalette(pal)
  2576. self.links_lay.addWidget(QtWidgets.QLabel('%s' % _("Soon ...")), alignment=QtCore.Qt.AlignCenter)
  2577. self.links_tab_layout.addWidget(links_scroll_area)
  2578. # HOW TO section
  2579. self.howto_tab = QtWidgets.QWidget()
  2580. self.howto_tab_layout = QtWidgets.QVBoxLayout(self.howto_tab)
  2581. self.howto_tab_layout.setContentsMargins(2, 2, 2, 2)
  2582. tab_widget.addTab(self.howto_tab, _("How To's"))
  2583. self.howto_lay = QtWidgets.QHBoxLayout()
  2584. howto_wdg = QtWidgets.QWidget()
  2585. howto_wdg.setLayout(self.howto_lay)
  2586. howto_scroll_area = QtWidgets.QScrollArea()
  2587. howto_scroll_area.setWidget(howto_wdg)
  2588. howto_scroll_area.setWidgetResizable(True)
  2589. howto_scroll_area.setFrameShape(QtWidgets.QFrame.NoFrame)
  2590. howto_scroll_area.setPalette(pal)
  2591. self.howto_lay.addWidget(QtWidgets.QLabel('%s' % _("Soon ...")), alignment=QtCore.Qt.AlignCenter)
  2592. self.howto_tab_layout.addWidget(howto_scroll_area)
  2593. # BUTTONS section
  2594. closebtn.clicked.connect(self.accept)
  2595. ReadmeDialog(app=self, parent=self.ui).exec_()
  2596. def install_bookmarks(self, book_dict=None):
  2597. """
  2598. Install the bookmarks actions in the Help menu -> Bookmarks
  2599. :param book_dict: a dict having the actions text as keys and the weblinks as the values
  2600. :return: None
  2601. """
  2602. if book_dict is None:
  2603. self.defaults["global_bookmarks"].update(
  2604. {
  2605. '1': ['FlatCAM', "http://flatcam.org"],
  2606. '2': ['Backup Site', ""]
  2607. }
  2608. )
  2609. else:
  2610. self.defaults["global_bookmarks"].clear()
  2611. self.defaults["global_bookmarks"].update(book_dict)
  2612. # first try to disconnect if somehow they get connected from elsewhere
  2613. for act in self.ui.menuhelp_bookmarks.actions():
  2614. try:
  2615. act.triggered.disconnect()
  2616. except TypeError:
  2617. pass
  2618. # clear all actions except the last one who is the Bookmark manager
  2619. if act is self.ui.menuhelp_bookmarks.actions()[-1]:
  2620. pass
  2621. else:
  2622. self.ui.menuhelp_bookmarks.removeAction(act)
  2623. bm_limit = int(self.defaults["global_bookmarks_limit"])
  2624. if self.defaults["global_bookmarks"]:
  2625. # order the self.defaults["global_bookmarks"] dict keys by the value as integer
  2626. # the whole convoluted things is because when serializing the self.defaults (on app close or save)
  2627. # the JSON is first making the keys as strings (therefore I have to use strings too
  2628. # or do the conversion :(
  2629. # )
  2630. # and it is ordering them (actually I want that to make the defaults easy to search within) but making
  2631. # the '10' entry jsut after '1' therefore ordering as strings
  2632. sorted_bookmarks = sorted(list(self.defaults["global_bookmarks"].items())[:bm_limit],
  2633. key=lambda x: int(x[0]))
  2634. for entry, bookmark in sorted_bookmarks:
  2635. title = bookmark[0]
  2636. weblink = bookmark[1]
  2637. act = QtWidgets.QAction(parent=self.ui.menuhelp_bookmarks)
  2638. act.setText(title)
  2639. act.setIcon(QtGui.QIcon(self.resource_location + '/link16.png'))
  2640. # from here: https://stackoverflow.com/questions/20390323/pyqt-dynamic-generate-qmenu-action-and-connect
  2641. if title == 'Backup Site' and weblink == "":
  2642. act.triggered.connect(self.on_backup_site)
  2643. else:
  2644. act.triggered.connect(lambda sig, link=weblink: webbrowser.open(link))
  2645. self.ui.menuhelp_bookmarks.insertAction(self.ui.menuhelp_bookmarks_manager, act)
  2646. self.ui.menuhelp_bookmarks_manager.triggered.connect(self.on_bookmarks_manager)
  2647. def on_bookmarks_manager(self):
  2648. """
  2649. Adds the bookmark manager in a Tab in Plot Area
  2650. :return:
  2651. """
  2652. for idx in range(self.ui.plot_tab_area.count()):
  2653. if self.ui.plot_tab_area.tabText(idx) == _("Bookmarks Manager"):
  2654. # there can be only one instance of Bookmark Manager at one time
  2655. return
  2656. # BookDialog(app=self, storage=self.defaults["global_bookmarks"], parent=self.ui).exec_()
  2657. self.book_dialog_tab = BookmarkManager(app=self, storage=self.defaults["global_bookmarks"], parent=self.ui)
  2658. self.book_dialog_tab.setObjectName("bookmarks_tab")
  2659. # add the tab if it was closed
  2660. self.ui.plot_tab_area.addTab(self.book_dialog_tab, _("Bookmarks Manager"))
  2661. # delete the absolute and relative position and messages in the infobar
  2662. # self.ui.position_label.setText("")
  2663. # self.ui.rel_position_label.setText("")
  2664. # hide coordinates toolbars in the infobar while in DB
  2665. self.ui.coords_toolbar.hide()
  2666. self.ui.delta_coords_toolbar.hide()
  2667. # Switch plot_area to preferences page
  2668. self.ui.plot_tab_area.setCurrentWidget(self.book_dialog_tab)
  2669. def on_backup_site(self):
  2670. msgbox = QtWidgets.QMessageBox()
  2671. msgbox.setText(_("This entry will resolve to another website if:\n\n"
  2672. "1. FlatCAM.org website is down\n"
  2673. "2. Someone forked FlatCAM project and wants to point\n"
  2674. "to his own website\n\n"
  2675. "If you can't get any informations about FlatCAM beta\n"
  2676. "use the YouTube channel link from the Help menu."))
  2677. msgbox.setWindowTitle(_("Alternative website"))
  2678. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/globe16.png'))
  2679. msgbox.setIcon(QtWidgets.QMessageBox.Question)
  2680. bt_yes = msgbox.addButton(_('Close'), QtWidgets.QMessageBox.YesRole)
  2681. msgbox.setDefaultButton(bt_yes)
  2682. msgbox.exec_()
  2683. # response = msgbox.clickedButton()
  2684. def final_save(self):
  2685. """
  2686. Callback for doing a preferences save to file whenever the application is about to quit.
  2687. If the project has changes, it will ask the user to save the project.
  2688. :return: None
  2689. """
  2690. if self.save_in_progress:
  2691. self.inform.emit('[WARNING_NOTCL] %s' % _("Application is saving the project. Please wait ..."))
  2692. return
  2693. if self.should_we_save and self.collection.get_list():
  2694. msgbox = QtWidgets.QMessageBox()
  2695. msgbox.setText(_("There are files/objects modified in FlatCAM. "
  2696. "\n"
  2697. "Do you want to Save the project?"))
  2698. msgbox.setWindowTitle(_("Save changes"))
  2699. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  2700. msgbox.setIcon(QtWidgets.QMessageBox.Question)
  2701. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  2702. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  2703. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  2704. msgbox.setDefaultButton(bt_yes)
  2705. msgbox.exec_()
  2706. response = msgbox.clickedButton()
  2707. if response == bt_yes:
  2708. try:
  2709. self.trayIcon.hide()
  2710. except Exception:
  2711. pass
  2712. self.on_file_saveprojectas(use_thread=True, quit_action=True)
  2713. elif response == bt_no:
  2714. try:
  2715. self.trayIcon.hide()
  2716. except Exception:
  2717. pass
  2718. self.quit_application()
  2719. elif response == bt_cancel:
  2720. return
  2721. else:
  2722. try:
  2723. self.trayIcon.hide()
  2724. except Exception:
  2725. pass
  2726. self.quit_application()
  2727. def quit_application(self):
  2728. """
  2729. Called (as a pyslot or not) when the application is quit.
  2730. :return: None
  2731. """
  2732. # close editors before quiting the app, if they are open
  2733. if self.geo_editor.editor_active is True:
  2734. self.geo_editor.deactivate()
  2735. try:
  2736. self.geo_editor.disconnect()
  2737. except TypeError:
  2738. pass
  2739. log.debug("App.quit_application() --> Geo Editor deactivated.")
  2740. if self.exc_editor.editor_active is True:
  2741. self.exc_editor.deactivate()
  2742. try:
  2743. self.grb_editor.disconnect()
  2744. except TypeError:
  2745. pass
  2746. log.debug("App.quit_application() --> Excellon Editor deactivated.")
  2747. if self.grb_editor.editor_active is True:
  2748. self.grb_editor.deactivate_grb_editor()
  2749. try:
  2750. self.exc_editor.disconnect()
  2751. except TypeError:
  2752. pass
  2753. log.debug("App.quit_application() --> Gerber Editor deactivated.")
  2754. # disconnect the mouse events
  2755. if self.is_legacy:
  2756. self.plotcanvas.graph_event_disconnect(self.mm)
  2757. self.plotcanvas.graph_event_disconnect(self.mp)
  2758. self.plotcanvas.graph_event_disconnect(self.mr)
  2759. self.plotcanvas.graph_event_disconnect(self.mdc)
  2760. self.plotcanvas.graph_event_disconnect(self.kp)
  2761. else:
  2762. self.mm = self.plotcanvas.graph_event_disconnect('mouse_move', self.on_mouse_move_over_plot)
  2763. self.mp = self.plotcanvas.graph_event_disconnect('mouse_press', self.on_mouse_click_over_plot)
  2764. self.mr = self.plotcanvas.graph_event_disconnect('mouse_release', self.on_mouse_click_release_over_plot)
  2765. self.mdc = self.plotcanvas.graph_event_disconnect('mouse_double_click',
  2766. self.on_mouse_double_click_over_plot)
  2767. self.kp = self.plotcanvas.graph_event_disconnect('key_press', self.ui.keyPressEvent)
  2768. self.preferencesUiManager.save_defaults(silent=True)
  2769. log.debug("App.quit_application() --> App Defaults saved.")
  2770. if self.cmd_line_headless != 1:
  2771. # save app state to file
  2772. stgs = QSettings("Open Source", "FlatCAM")
  2773. stgs.setValue('saved_gui_state', self.ui.saveState())
  2774. stgs.setValue('maximized_gui', self.ui.isMaximized())
  2775. stgs.setValue(
  2776. 'language',
  2777. self.ui.general_defaults_form.general_app_group.language_cb.get_value()
  2778. )
  2779. stgs.setValue(
  2780. 'notebook_font_size',
  2781. self.ui.general_defaults_form.general_app_set_group.notebook_font_size_spinner.get_value()
  2782. )
  2783. stgs.setValue(
  2784. 'axis_font_size',
  2785. self.ui.general_defaults_form.general_app_set_group.axis_font_size_spinner.get_value()
  2786. )
  2787. stgs.setValue(
  2788. 'textbox_font_size',
  2789. self.ui.general_defaults_form.general_app_set_group.textbox_font_size_spinner.get_value()
  2790. )
  2791. stgs.setValue(
  2792. 'hud_font_size',
  2793. self.ui.general_defaults_form.general_app_set_group.hud_font_size_spinner.get_value()
  2794. )
  2795. stgs.setValue('toolbar_lock', self.ui.lock_action.isChecked())
  2796. stgs.setValue(
  2797. 'machinist',
  2798. 1 if self.ui.general_defaults_form.general_app_set_group.machinist_cb.get_value() else 0
  2799. )
  2800. # This will write the setting to the platform specific storage.
  2801. del stgs
  2802. log.debug("App.quit_application() --> App UI state saved.")
  2803. # try to quit the Socket opened by ArgsThread class
  2804. try:
  2805. # self.new_launch.thread_exit = True
  2806. # self.new_launch.listener.close()
  2807. self.new_launch.stop.emit()
  2808. except Exception as err:
  2809. log.debug("App.quit_application() --> %s" % str(err))
  2810. # try to quit the QThread that run ArgsThread class
  2811. try:
  2812. # del self.new_launch
  2813. self.listen_th.quit()
  2814. except Exception as e:
  2815. log.debug("App.quit_application() --> %s" % str(e))
  2816. # terminate workers
  2817. # self.workers.__del__()
  2818. self.clear_pool()
  2819. # quit app by signalling for self.kill_app() method
  2820. # self.close_app_signal.emit()
  2821. QtWidgets.qApp.quit()
  2822. sys.exit(0)
  2823. # When the main event loop is not started yet in which case the qApp.quit() will do nothing
  2824. # we use the following command
  2825. # minor_v = sys.version_info.minor
  2826. # if minor_v < 8:
  2827. # # make sure that the app closes
  2828. # sys.exit(0)
  2829. # else:
  2830. # os._exit(0) # fix to work with Python 3.8
  2831. @staticmethod
  2832. def kill_app():
  2833. QtWidgets.qApp.quit()
  2834. # When the main event loop is not started yet in which case the qApp.quit() will do nothing
  2835. # we use the following command
  2836. sys.exit(0)
  2837. def on_portable_checked(self, state):
  2838. """
  2839. Callback called when the checkbox in Preferences GUI is checked.
  2840. It will set the application as portable by creating the preferences and recent files in the
  2841. 'config' folder found in the FlatCAM installation folder.
  2842. :param state: boolean, the state of the checkbox when clicked/checked
  2843. :return:
  2844. """
  2845. line_no = 0
  2846. data = None
  2847. if sys.platform != 'win32':
  2848. # this won't work in Linux or MacOS
  2849. return
  2850. # test if the app was frozen and choose the path for the configuration file
  2851. if getattr(sys, "frozen", False) is True:
  2852. current_data_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config'
  2853. else:
  2854. current_data_path = os.path.dirname(os.path.realpath(__file__)) + '\\config'
  2855. config_file = current_data_path + '\\configuration.txt'
  2856. try:
  2857. with open(config_file, 'r') as f:
  2858. try:
  2859. data = f.readlines()
  2860. except Exception as e:
  2861. log.debug('App.__init__() -->%s' % str(e))
  2862. return
  2863. except FileNotFoundError:
  2864. pass
  2865. for line in data:
  2866. line = line.strip('\n')
  2867. param = str(line).rpartition('=')
  2868. if param[0] == 'portable':
  2869. break
  2870. line_no += 1
  2871. if state:
  2872. data[line_no] = 'portable=True\n'
  2873. # create the new defauults files
  2874. # create current_defaults.FlatConfig file if there is none
  2875. try:
  2876. f = open(current_data_path + '/current_defaults.FlatConfig')
  2877. f.close()
  2878. except IOError:
  2879. App.log.debug('Creating empty current_defaults.FlatConfig')
  2880. f = open(current_data_path + '/current_defaults.FlatConfig', 'w')
  2881. json.dump({}, f)
  2882. f.close()
  2883. # create factory_defaults.FlatConfig file if there is none
  2884. try:
  2885. f = open(current_data_path + '/factory_defaults.FlatConfig')
  2886. f.close()
  2887. except IOError:
  2888. App.log.debug('Creating empty factory_defaults.FlatConfig')
  2889. f = open(current_data_path + '/factory_defaults.FlatConfig', 'w')
  2890. json.dump({}, f)
  2891. f.close()
  2892. try:
  2893. f = open(current_data_path + '/recent.json')
  2894. f.close()
  2895. except IOError:
  2896. App.log.debug('Creating empty recent.json')
  2897. f = open(current_data_path + '/recent.json', 'w')
  2898. json.dump([], f)
  2899. f.close()
  2900. try:
  2901. fp = open(current_data_path + '/recent_projects.json')
  2902. fp.close()
  2903. except IOError:
  2904. App.log.debug('Creating empty recent_projects.json')
  2905. fp = open(current_data_path + '/recent_projects.json', 'w')
  2906. json.dump([], fp)
  2907. fp.close()
  2908. # save the current defaults to the new defaults file
  2909. self.preferencesUiManager.save_defaults(silent=True, data_path=current_data_path)
  2910. else:
  2911. data[line_no] = 'portable=False\n'
  2912. with open(config_file, 'w') as f:
  2913. f.writelines(data)
  2914. def on_register_files(self, obj_type=None):
  2915. """
  2916. Called whenever there is a need to register file extensions with FlatCAM.
  2917. Works only in Windows and should be called only when FlatCAM is run in Windows.
  2918. :param obj_type: the type of object to be register for.
  2919. Can be: 'gerber', 'excellon' or 'gcode'. 'geometry' is not used for the moment.
  2920. :return: None
  2921. """
  2922. log.debug("Manufacturing files extensions are registered with FlatCAM.")
  2923. new_reg_path = 'Software\\Classes\\'
  2924. # find if the current user is admin
  2925. try:
  2926. is_admin = os.getuid() == 0
  2927. except AttributeError:
  2928. is_admin = ctypes.windll.shell32.IsUserAnAdmin() == 1
  2929. if is_admin is True:
  2930. root_path = winreg.HKEY_LOCAL_MACHINE
  2931. else:
  2932. root_path = winreg.HKEY_CURRENT_USER
  2933. # create the keys
  2934. def set_reg(name, root_pth, new_reg_path, value):
  2935. try:
  2936. winreg.CreateKey(root_pth, new_reg_path)
  2937. with winreg.OpenKey(root_pth, new_reg_path, 0, winreg.KEY_WRITE) as registry_key:
  2938. winreg.SetValueEx(registry_key, name, 0, winreg.REG_SZ, value)
  2939. return True
  2940. except WindowsError:
  2941. return False
  2942. # delete key in registry
  2943. def delete_reg(root_pth, reg_path, key_to_del):
  2944. key_to_del_path = reg_path + key_to_del
  2945. try:
  2946. winreg.DeleteKey(root_pth, key_to_del_path)
  2947. return True
  2948. except WindowsError:
  2949. return False
  2950. if obj_type is None or obj_type == 'excellon':
  2951. exc_list = \
  2952. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  2953. exc_list = [x for x in exc_list if x != '']
  2954. # register all keys in the Preferences window
  2955. for ext in exc_list:
  2956. new_k = new_reg_path + '.%s' % ext
  2957. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  2958. # and unregister those that are no longer in the Preferences windows but are in the file
  2959. for ext in self.defaults["fa_excellon"].replace(' ', '').split(','):
  2960. if ext not in exc_list:
  2961. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  2962. # now write the updated extensions to the self.defaults
  2963. # new_ext = ''
  2964. # for ext in exc_list:
  2965. # new_ext = new_ext + ext + ', '
  2966. # self.defaults["fa_excellon"] = new_ext
  2967. self.inform.emit('[success] %s' % _("Selected Excellon file extensions registered with FlatCAM."))
  2968. if obj_type is None or obj_type == 'gcode':
  2969. gco_list = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  2970. gco_list = [x for x in gco_list if x != '']
  2971. # register all keys in the Preferences window
  2972. for ext in gco_list:
  2973. new_k = new_reg_path + '.%s' % ext
  2974. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  2975. # and unregister those that are no longer in the Preferences windows but are in the file
  2976. for ext in self.defaults["fa_gcode"].replace(' ', '').split(','):
  2977. if ext not in gco_list:
  2978. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  2979. # now write the updated extensions to the self.defaults
  2980. # new_ext = ''
  2981. # for ext in gco_list:
  2982. # new_ext = new_ext + ext + ', '
  2983. # self.defaults["fa_gcode"] = new_ext
  2984. self.inform.emit('[success] %s' %
  2985. _("Selected GCode file extensions registered with FlatCAM."))
  2986. if obj_type is None or obj_type == 'gerber':
  2987. grb_list = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  2988. grb_list = [x for x in grb_list if x != '']
  2989. # register all keys in the Preferences window
  2990. for ext in grb_list:
  2991. new_k = new_reg_path + '.%s' % ext
  2992. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  2993. # and unregister those that are no longer in the Preferences windows but are in the file
  2994. for ext in self.defaults["fa_gerber"].replace(' ', '').split(','):
  2995. if ext not in grb_list:
  2996. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  2997. # now write the updated extensions to the self.defaults
  2998. # new_ext = ''
  2999. # for ext in grb_list:
  3000. # new_ext = new_ext + ext + ', '
  3001. # self.defaults["fa_gerber"] = new_ext
  3002. self.inform.emit('[success] %s' %
  3003. _("Selected Gerber file extensions registered with FlatCAM."))
  3004. def add_extension(self, ext_type):
  3005. """
  3006. Add a file extension to the list for a specific object
  3007. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  3008. :return:
  3009. """
  3010. if ext_type == 'excellon':
  3011. new_ext = self.ui.util_defaults_form.fa_excellon_group.ext_entry.get_value()
  3012. if new_ext == '':
  3013. return
  3014. old_val = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  3015. if new_ext in old_val:
  3016. return
  3017. old_val.append(new_ext)
  3018. old_val.sort()
  3019. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(old_val))
  3020. if ext_type == 'gcode':
  3021. new_ext = self.ui.util_defaults_form.fa_gcode_group.ext_entry.get_value()
  3022. if new_ext == '':
  3023. return
  3024. old_val = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  3025. if new_ext in old_val:
  3026. return
  3027. old_val.append(new_ext)
  3028. old_val.sort()
  3029. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(old_val))
  3030. if ext_type == 'gerber':
  3031. new_ext = self.ui.util_defaults_form.fa_gerber_group.ext_entry.get_value()
  3032. if new_ext == '':
  3033. return
  3034. old_val = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  3035. if new_ext in old_val:
  3036. return
  3037. old_val.append(new_ext)
  3038. old_val.sort()
  3039. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(old_val))
  3040. if ext_type == 'keyword':
  3041. new_kw = self.ui.util_defaults_form.kw_group.kw_entry.get_value()
  3042. if new_kw == '':
  3043. return
  3044. old_val = self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  3045. if new_kw in old_val:
  3046. return
  3047. old_val.append(new_kw)
  3048. old_val.sort()
  3049. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(old_val))
  3050. # update the self.myKeywords so the model is updated
  3051. self.autocomplete_kw_list = \
  3052. self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  3053. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  3054. self.shell._edit.set_model_data(self.myKeywords)
  3055. def del_extension(self, ext_type):
  3056. """
  3057. Remove a file extension from the list for a specific object
  3058. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  3059. :return:
  3060. """
  3061. if ext_type == 'excellon':
  3062. new_ext = self.ui.util_defaults_form.fa_excellon_group.ext_entry.get_value()
  3063. if new_ext == '':
  3064. return
  3065. old_val = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  3066. if new_ext not in old_val:
  3067. return
  3068. old_val.remove(new_ext)
  3069. old_val.sort()
  3070. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(old_val))
  3071. if ext_type == 'gcode':
  3072. new_ext = self.ui.util_defaults_form.fa_gcode_group.ext_entry.get_value()
  3073. if new_ext == '':
  3074. return
  3075. old_val = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  3076. if new_ext not in old_val:
  3077. return
  3078. old_val.remove(new_ext)
  3079. old_val.sort()
  3080. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(old_val))
  3081. if ext_type == 'gerber':
  3082. new_ext = self.ui.util_defaults_form.fa_gerber_group.ext_entry.get_value()
  3083. if new_ext == '':
  3084. return
  3085. old_val = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  3086. if new_ext not in old_val:
  3087. return
  3088. old_val.remove(new_ext)
  3089. old_val.sort()
  3090. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(old_val))
  3091. if ext_type == 'keyword':
  3092. new_kw = self.ui.util_defaults_form.kw_group.kw_entry.get_value()
  3093. if new_kw == '':
  3094. return
  3095. old_val = self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  3096. if new_kw not in old_val:
  3097. return
  3098. old_val.remove(new_kw)
  3099. old_val.sort()
  3100. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(old_val))
  3101. # update the self.myKeywords so the model is updated
  3102. self.autocomplete_kw_list = \
  3103. self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  3104. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  3105. self.shell._edit.set_model_data(self.myKeywords)
  3106. def restore_extensions(self, ext_type):
  3107. """
  3108. Restore all file extensions associations with FlatCAM, for a specific object
  3109. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  3110. :return:
  3111. """
  3112. if ext_type == 'excellon':
  3113. # don't add 'txt' to the associations (too many files are .txt and not Excellon) but keep it in the list
  3114. # for the ability to open Excellon files with .txt extension
  3115. new_exc_list = deepcopy(self.exc_list)
  3116. try:
  3117. new_exc_list.remove('txt')
  3118. except ValueError:
  3119. pass
  3120. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(new_exc_list))
  3121. if ext_type == 'gcode':
  3122. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(self.gcode_list))
  3123. if ext_type == 'gerber':
  3124. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(self.grb_list))
  3125. if ext_type == 'keyword':
  3126. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(self.default_keywords))
  3127. # update the self.myKeywords so the model is updated
  3128. self.autocomplete_kw_list = self.default_keywords
  3129. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  3130. self.shell._edit.set_model_data(self.myKeywords)
  3131. def delete_all_extensions(self, ext_type):
  3132. """
  3133. Delete all file extensions associations with FlatCAM, for a specific object
  3134. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  3135. :return:
  3136. """
  3137. if ext_type == 'excellon':
  3138. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value('')
  3139. if ext_type == 'gcode':
  3140. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value('')
  3141. if ext_type == 'gerber':
  3142. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value('')
  3143. if ext_type == 'keyword':
  3144. self.ui.util_defaults_form.kw_group.kw_list_text.set_value('')
  3145. # update the self.myKeywords so the model is updated
  3146. self.myKeywords = self.tcl_commands_list + self.tcl_keywords
  3147. self.shell._edit.set_model_data(self.myKeywords)
  3148. def on_edit_join(self, name=None):
  3149. """
  3150. Callback for Edit->Join. Joins the selected geometry objects into
  3151. a new one.
  3152. :return: None
  3153. """
  3154. self.defaults.report_usage("on_edit_join()")
  3155. obj_name_single = str(name) if name else "Combo_SingleGeo"
  3156. obj_name_multi = str(name) if name else "Combo_MultiGeo"
  3157. geo_type_set = set()
  3158. objs = self.collection.get_selected()
  3159. if len(objs) < 2:
  3160. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  3161. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  3162. return 'fail'
  3163. for obj in objs:
  3164. geo_type_set.add(obj.multigeo)
  3165. # if len(geo_type_list) == 1 means that all list elements are the same
  3166. if len(geo_type_set) != 1:
  3167. self.inform.emit('[ERROR] %s' %
  3168. _("Failed join. The Geometry objects are of different types.\n"
  3169. "At least one is MultiGeo type and the other is SingleGeo type. A possibility is to "
  3170. "convert from one to another and retry joining \n"
  3171. "but in the case of converting from MultiGeo to SingleGeo, informations may be lost and "
  3172. "the result may not be what was expected. \n"
  3173. "Check the generated GCODE."))
  3174. return
  3175. fuse_tools = self.defaults["geometry_merge_fuse_tools"]
  3176. # if at least one True object is in the list then due of the previous check, all list elements are True objects
  3177. if True in geo_type_set:
  3178. def initialize(geo_obj, app):
  3179. GeometryObject.merge(geo_list=objs, geo_final=geo_obj, multigeo=True, fuse_tools=fuse_tools)
  3180. app.inform.emit('[success] %s.' % _("Geometry merging finished"))
  3181. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  3182. for v in geo_obj.tools.values():
  3183. v['data']['name'] = obj_name_multi
  3184. self.app_obj.new_object("geometry", obj_name_multi, initialize)
  3185. else:
  3186. def initialize(geo_obj, app):
  3187. GeometryObject.merge(geo_list=objs, geo_final=geo_obj, multigeo=False, fuse_tools=fuse_tools)
  3188. app.inform.emit('[success] %s.' % _("Geometry merging finished"))
  3189. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  3190. for v in geo_obj.tools.values():
  3191. v['data']['name'] = obj_name_single
  3192. self.app_obj.new_object("geometry", obj_name_single, initialize)
  3193. self.should_we_save = True
  3194. def on_edit_join_exc(self):
  3195. """
  3196. Callback for Edit->Join Excellon. Joins the selected Excellon objects into
  3197. a new Excellon.
  3198. :return: None
  3199. """
  3200. self.defaults.report_usage("on_edit_join_exc()")
  3201. objs = self.collection.get_selected()
  3202. for obj in objs:
  3203. if not isinstance(obj, ExcellonObject):
  3204. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Excellon joining works only on Excellon objects."))
  3205. return
  3206. if len(objs) < 2:
  3207. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  3208. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  3209. return 'fail'
  3210. fuse_tools = self.defaults["excellon_merge_fuse_tools"]
  3211. def initialize(exc_obj, app):
  3212. ExcellonObject.merge(exc_list=objs, exc_final=exc_obj, decimals=self.decimals, fuse_tools=fuse_tools)
  3213. app.inform.emit('[success] %s.' % _("Excellon merging finished"))
  3214. self.app_obj.new_object("excellon", 'Combo_Excellon', initialize)
  3215. self.should_we_save = True
  3216. def on_edit_join_grb(self):
  3217. """
  3218. Callback for Edit->Join Gerber. Joins the selected Gerber objects into
  3219. a new Gerber object.
  3220. :return: None
  3221. """
  3222. self.defaults.report_usage("on_edit_join_grb()")
  3223. objs = self.collection.get_selected()
  3224. for obj in objs:
  3225. if not isinstance(obj, GerberObject):
  3226. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Gerber joining works only on Gerber objects."))
  3227. return
  3228. if len(objs) < 2:
  3229. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  3230. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  3231. return 'fail'
  3232. def initialize(grb_obj, app):
  3233. GerberObject.merge(grb_list=objs, grb_final=grb_obj)
  3234. app.inform.emit('[success] %s.' % _("Gerber merging finished"))
  3235. self.app_obj.new_object("gerber", 'Combo_Gerber', initialize)
  3236. self.should_we_save = True
  3237. def on_convert_singlegeo_to_multigeo(self):
  3238. """
  3239. Called for converting a Geometry object from single-geo to multi-geo.
  3240. Single-geo Geometry objects store their geometry data into self.solid_geometry.
  3241. Multi-geo Geometry objects store their geometry data into the self.tools dictionary, each key (a tool actually)
  3242. having as a value another dictionary. This value dictionary has one of it's keys 'solid_geometry' which holds
  3243. the solid-geometry of that tool.
  3244. :return: None
  3245. """
  3246. self.defaults.report_usage("on_convert_singlegeo_to_multigeo()")
  3247. obj = self.collection.get_active()
  3248. if obj is None:
  3249. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Select a Geometry Object and try again."))
  3250. return
  3251. if not isinstance(obj, GeometryObject):
  3252. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Expected a GeometryObject, got"), type(obj)))
  3253. return
  3254. obj.multigeo = True
  3255. for tooluid, dict_value in obj.tools.items():
  3256. dict_value['solid_geometry'] = deepcopy(obj.solid_geometry)
  3257. if not isinstance(obj.solid_geometry, list):
  3258. obj.solid_geometry = [obj.solid_geometry]
  3259. # obj.solid_geometry[:] = []
  3260. obj.plot()
  3261. self.should_we_save = True
  3262. self.inform.emit('[success] %s' % _("A Geometry object was converted to MultiGeo type."))
  3263. def on_convert_multigeo_to_singlegeo(self):
  3264. """
  3265. Called for converting a Geometry object from multi-geo to single-geo.
  3266. Single-geo Geometry objects store their geometry data into self.solid_geometry.
  3267. Multi-geo Geometry objects store their geometry data into the self.tools dictionary, each key (a tool actually)
  3268. having as a value another dictionary. This value dictionary has one of it's keys 'solid_geometry' which holds
  3269. the solid-geometry of that tool.
  3270. :return: None
  3271. """
  3272. self.defaults.report_usage("on_convert_multigeo_to_singlegeo()")
  3273. obj = self.collection.get_active()
  3274. if obj is None:
  3275. self.inform.emit('[ERROR_NOTCL] %s' %
  3276. _("Failed. Select a Geometry Object and try again."))
  3277. return
  3278. if not isinstance(obj, GeometryObject):
  3279. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  3280. (_("Expected a GeometryObject, got"), type(obj)))
  3281. return
  3282. obj.multigeo = False
  3283. total_solid_geometry = []
  3284. for tooluid, dict_value in obj.tools.items():
  3285. total_solid_geometry += deepcopy(dict_value['solid_geometry'])
  3286. # clear the original geometry
  3287. dict_value['solid_geometry'][:] = []
  3288. obj.solid_geometry = deepcopy(total_solid_geometry)
  3289. obj.plot()
  3290. self.should_we_save = True
  3291. self.inform.emit('[success] %s' %
  3292. _("A Geometry object was converted to SingleGeo type."))
  3293. def on_defaults_dict_change(self, field):
  3294. """
  3295. Called whenever a key changed in the self.defaults dictionary. It will set the required GUI element in the
  3296. Edit -> Preferences tab window.
  3297. :param field: the key of the self.defaults dictionary that was changed.
  3298. :return: None
  3299. """
  3300. self.preferencesUiManager.defaults_write_form_field(field=field)
  3301. if field == "units":
  3302. self.set_screen_units(self.defaults['units'])
  3303. def set_screen_units(self, units):
  3304. """
  3305. Set the FlatCAM units on the status bar.
  3306. :param units: the new measuring units to be displayed in FlatCAM's status bar.
  3307. :return: None
  3308. """
  3309. self.ui.units_label.setText("[" + units.lower() + "]")
  3310. def on_toggle_units_click(self):
  3311. try:
  3312. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.disconnect()
  3313. except (TypeError, AttributeError):
  3314. pass
  3315. if self.defaults["units"] == 'MM':
  3316. self.ui.general_defaults_form.general_app_group.units_radio.set_value("IN")
  3317. else:
  3318. self.ui.general_defaults_form.general_app_group.units_radio.set_value("MM")
  3319. self.on_toggle_units(no_pref=True)
  3320. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.connect(
  3321. lambda: self.on_toggle_units(no_pref=False))
  3322. def scale_defaults(self, sfactor, dimensions):
  3323. for dim in dimensions:
  3324. if dim in ['geometry_cnctooldia', 'tools_ncc_tools', 'tools_solderpaste_tools', 'tools_iso_tooldia',
  3325. 'tools_paint_tooldia', 'tools_transform_ref_point', 'tools_cal_toolchange_xy',
  3326. 'gerber_editor_newdim', 'tools_drill_toolchangexy', 'tools_drill_endxy',
  3327. 'geometry_toolchangexy', 'geometry_endxy', 'tools_solderpaste_xy_toolchange']:
  3328. if not self.defaults[dim] or self.defaults[dim] == '':
  3329. continue
  3330. if isinstance(self.defaults[dim], str):
  3331. try:
  3332. tools_diameters = eval(self.defaults[dim])
  3333. except Exception as e:
  3334. log.debug("App.on_toggle_units().scale_defaults() lists --> %s" % str(e))
  3335. continue
  3336. elif isinstance(self.defaults[dim], (float, int)):
  3337. tools_diameters = [self.defaults[dim]]
  3338. else:
  3339. tools_diameters = list(self.defaults[dim])
  3340. if isinstance(tools_diameters, (tuple, list)):
  3341. pass
  3342. elif isinstance(tools_diameters, (int, float)):
  3343. tools_diameters = [self.defaults[dim]]
  3344. else:
  3345. continue
  3346. td_len = len(tools_diameters)
  3347. conv_list = []
  3348. for t in range(td_len):
  3349. conv_list.append(self.dec_format(float(tools_diameters[t]) * sfactor, self.decimals))
  3350. self.defaults[dim] = conv_list
  3351. elif dim in ['global_gridx', 'global_gridy']:
  3352. # format the number of decimals to the one specified in self.decimals
  3353. try:
  3354. val = float(self.defaults[dim]) * sfactor
  3355. except Exception as e:
  3356. log.debug('App.on_toggle_units().scale_defaults() grids --> %s' % str(e))
  3357. continue
  3358. self.defaults[dim] = self.dec_format(val, self.decimals)
  3359. else:
  3360. # the number of decimals for the rest is kept unchanged
  3361. if self.defaults[dim]:
  3362. try:
  3363. val = float(self.defaults[dim]) * sfactor
  3364. except Exception as e:
  3365. log.debug(
  3366. 'App.on_toggle_units().scale_defaults() standard --> Value: %s %s' % (str(dim), str(e))
  3367. )
  3368. continue
  3369. self.defaults[dim] = self.dec_format(val, self.decimals)
  3370. def on_toggle_units(self, no_pref=False):
  3371. """
  3372. Callback for the Units radio-button change in the Preferences tab.
  3373. Changes the application's default units adn for the project too.
  3374. If changing the project's units, the change propagates to all of
  3375. the objects in the project.
  3376. :return: None
  3377. """
  3378. self.defaults.report_usage("on_toggle_units")
  3379. if self.toggle_units_ignore:
  3380. return
  3381. new_units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  3382. # If option is the same, then ignore
  3383. if new_units == self.defaults["units"].upper():
  3384. self.log.debug("on_toggle_units(): Same as previous, ignoring.")
  3385. return
  3386. # Keys in self.defaults for which to scale their values
  3387. dimensions = [
  3388. # Global
  3389. 'global_gridx', 'global_gridy', 'global_snap_max', "global_tolerance",
  3390. 'global_tpdf_bmargin', 'global_tpdf_tmargin', 'global_tpdf_rmargin', 'global_tpdf_lmargin',
  3391. # Gerber Object
  3392. 'gerber_noncoppermargin', 'gerber_bboxmargin',
  3393. # Gerber Editor
  3394. "gerber_editor_newsize", "gerber_editor_lin_pitch", "gerber_editor_buff_f",
  3395. "gerber_editor_newdim", "gerber_editor_ma_low", "gerber_editor_ma_high",
  3396. # Excellon Object
  3397. "excellon_milling_dia", 'excellon_tooldia', 'excellon_slot_tooldia',
  3398. # Excellon Editor
  3399. "excellon_editor_newdia", "excellon_editor_lin_pitch", "excellon_editor_slot_lin_pitch",
  3400. "excellon_editor_slot_length",
  3401. # Geometry Object
  3402. 'geometry_cutz', "geometry_depthperpass", 'geometry_travelz', 'geometry_feedrate',
  3403. 'geometry_feedrate_rapid', "geometry_toolchangez", "geometry_feedrate_z",
  3404. "geometry_toolchangexy", 'geometry_cnctooldia', 'geometry_endz', 'geometry_endxy',
  3405. "geometry_extracut_length", "geometry_z_pdepth",
  3406. "geometry_feedrate_probe", "geometry_startz", "geometry_segx", "geometry_segy", "geometry_area_overz",
  3407. # CNCJob Object
  3408. 'cncjob_tooldia', "cncjob_al_travelz", "cncjob_al_probe_depth", "cncjob_al_grbl_jog_step",
  3409. "cncjob_al_grbl_jog_fr", "cncjob_al_grbl_travelz",
  3410. # Isolation Tool
  3411. "tools_iso_tool_vtipdia", 'tools_iso_tooldia', "tools_iso_tool_cutz",
  3412. # Drilling Tool
  3413. 'tools_drill_cutz', 'tools_drill_depthperpass', 'tools_drill_travelz', 'tools_drill_endz',
  3414. 'tools_drill_endxy', 'tools_drill_feedrate_z', 'tools_drill_toolchangez', "tools_drill_drill_overlap",
  3415. 'tools_drill_offset', "tools_drill_toolchangexy", "tools_drill_startz", 'tools_drill_feedrate_rapid',
  3416. "tools_drill_feedrate_probe", "tools_drill_z_pdepth", "tools_drill_area_overz",
  3417. # NCC Tool
  3418. "tools_ncc_tools", "tools_ncc_margin", "tools_ncc_offset_value", "tools_ncc_cutz", "tools_ncc_tipdia",
  3419. "tools_ncc_newdia",
  3420. # Cutout Tool
  3421. "tools_cutout_tooldia", 'tools_cutout_margin', "tools_cutout_z", "tools_cutout_depthperpass",
  3422. 'tools_cutout_gapsize', 'tools_cutout_gap_depth', 'tools_cutout_mb_dia', 'tools_cutout_mb_spacing',
  3423. # Paint Tool
  3424. "tools_paint_tooldia", 'tools_paint_offset', "tools_paint_cutz", "tools_paint_tipdia", "tools_paint_newdia",
  3425. # 2Sided Tool
  3426. "tools_2sided_drilldia",
  3427. # Film Tool
  3428. "tools_film_boundary", "tools_film_scale_stroke",
  3429. # Panel Tool
  3430. "tools_panelize_spacing_columns", "tools_panelize_spacing_rows", "tools_panelize_constrainx",
  3431. "tools_panelize_constrainy",
  3432. # Calculators Tool
  3433. "tools_calc_vshape_tip_dia", "tools_calc_vshape_cut_z",
  3434. # Transform Tool
  3435. "tools_transform_ref_point", "tools_transform_offset_x", "tools_transform_offset_y",
  3436. "tools_transform_buffer_dis",
  3437. # SolderPaste Tool
  3438. "tools_solderpaste_tools", "tools_solderpaste_new", "tools_solderpaste_z_start",
  3439. "tools_solderpaste_z_dispense", "tools_solderpaste_z_stop", "tools_solderpaste_z_travel",
  3440. "tools_solderpaste_z_toolchange", "tools_solderpaste_xy_toolchange", "tools_solderpaste_frxy",
  3441. "tools_solderpaste_frz", "tools_solderpaste_frz_dispense",
  3442. # Corner Markers Tool
  3443. "tools_corners_thickness", "tools_corners_length", "tools_corners_margin",
  3444. # Check Rules Tool
  3445. "tools_cr_trace_size_val", "tools_cr_c2c_val", "tools_cr_c2o_val", "tools_cr_s2s_val", "tools_cr_s2sm_val",
  3446. "tools_cr_s2o_val", "tools_cr_sm2sm_val", "tools_cr_ri_val", "tools_cr_h2h_val", "tools_cr_dh_val",
  3447. # QRCode Tool
  3448. "tools_qrcode_border_size",
  3449. # Copper Thieving Tool
  3450. "tools_copper_thieving_clearance", "tools_copper_thieving_margin",
  3451. "tools_copper_thieving_dots_dia", "tools_copper_thieving_dots_spacing",
  3452. "tools_copper_thieving_squares_size", "tools_copper_thieving_squares_spacing",
  3453. "tools_copper_thieving_lines_size", "tools_copper_thieving_lines_spacing",
  3454. "tools_copper_thieving_rb_margin", "tools_copper_thieving_rb_thickness",
  3455. "tools_copper_thieving_mask_clearance",
  3456. # Fiducials Tool
  3457. "tools_fiducials_dia", "tools_fiducials_margin", "tools_fiducials_line_thickness",
  3458. # Calibration Tool
  3459. "tools_cal_travelz", "tools_cal_verz", "tools_cal_toolchangez", "tools_cal_toolchange_xy",
  3460. # Drills Extraction Tool
  3461. "tools_edrills_hole_fixed_dia", "tools_edrills_circular_ring", "tools_edrills_oblong_ring",
  3462. "tools_edrills_square_ring", "tools_edrills_rectangular_ring", "tools_edrills_others_ring",
  3463. # Punch Gerber Tool
  3464. "tools_punch_hole_fixed_dia", "tools_punch_circular_ring", "tools_punch_oblong_ring",
  3465. "tools_punch_square_ring", "tools_punch_rectangular_ring", "tools_punch_others_ring",
  3466. # Invert Gerber Tool
  3467. "tools_invert_margin",
  3468. ]
  3469. # The scaling factor depending on choice of units.
  3470. factor = 25.4 if new_units == 'MM' else 1 / 25.4
  3471. # Changing project units. Warn user.
  3472. msgbox = QtWidgets.QMessageBox()
  3473. msgbox.setWindowTitle(_("Toggle Units"))
  3474. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/toggle_units32.png'))
  3475. msgbox.setIcon(QtWidgets.QMessageBox.Question)
  3476. msgbox.setText(_("Changing the units of the project\n"
  3477. "will scale all objects.\n\n"
  3478. "Do you want to continue?"))
  3479. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  3480. msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  3481. msgbox.setDefaultButton(bt_ok)
  3482. msgbox.exec_()
  3483. response = msgbox.clickedButton()
  3484. if response == bt_ok:
  3485. if no_pref is False:
  3486. self.preferencesUiManager.defaults_read_form()
  3487. self.scale_defaults(factor, dimensions)
  3488. self.preferencesUiManager.defaults_write_form(fl_units=new_units)
  3489. self.defaults["units"] = new_units
  3490. # update the defaults from form, some may assume that the conversion is enough and it's not
  3491. self.on_options_app2project()
  3492. # update the objects
  3493. for obj in self.collection.get_list():
  3494. obj.convert_units(new_units)
  3495. # make that the properties stored in the object are also updated
  3496. self.app_obj.object_changed.emit(obj)
  3497. # rebuild the object UI
  3498. obj.build_ui()
  3499. # change this only if the workspace is active
  3500. if self.defaults['global_workspace'] is True:
  3501. self.plotcanvas.draw_workspace(pagesize=self.defaults['global_workspaceT'])
  3502. # adjust the grid values on the main toolbar
  3503. val_x = float(self.defaults['global_gridx']) * factor
  3504. val_y = val_x if self.ui.grid_gap_link_cb.isChecked() else float(self.defaults['global_gridx']) * factor
  3505. current = self.collection.get_active()
  3506. if current is not None:
  3507. # the transfer of converted values to the UI form for Geometry is done local in the FlatCAMObj.py
  3508. if not isinstance(current, GeometryObject):
  3509. current.to_form()
  3510. # replot all objects
  3511. self.plot_all()
  3512. # set the status labels to reflect the current FlatCAM units
  3513. self.set_screen_units(new_units)
  3514. # signal to the app that we changed the object properties and it should save the project
  3515. self.should_we_save = True
  3516. self.inform.emit('[success] %s: %s' % (_("Converted units to"), new_units))
  3517. else:
  3518. # Undo toggling
  3519. self.toggle_units_ignore = True
  3520. if self.defaults['units'].upper() == 'MM':
  3521. self.ui.general_defaults_form.general_app_group.units_radio.set_value('IN')
  3522. else:
  3523. self.ui.general_defaults_form.general_app_group.units_radio.set_value('MM')
  3524. self.toggle_units_ignore = False
  3525. # store the grid values so they are not changed in the next step
  3526. val_x = float(self.defaults['global_gridx'])
  3527. val_y = float(self.defaults['global_gridy'])
  3528. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  3529. self.preferencesUiManager.defaults_read_form()
  3530. # the self.preferencesUiManager.defaults_read_form() will update all defaults values
  3531. # in self.defaults from the GUI elements but
  3532. # I don't want it for the grid values, so I update them here
  3533. self.defaults['global_gridx'] = val_x
  3534. self.defaults['global_gridy'] = val_y
  3535. self.ui.grid_gap_x_entry.set_value(val_x, decimals=self.decimals)
  3536. self.ui.grid_gap_y_entry.set_value(val_y, decimals=self.decimals)
  3537. def on_deselect_all(self):
  3538. self.collection.set_all_inactive()
  3539. self.delete_selection_shape()
  3540. def on_workspace_modified(self):
  3541. # self.save_defaults(silent=True)
  3542. self.plotcanvas.delete_workspace()
  3543. self.preferencesUiManager.defaults_read_form()
  3544. self.plotcanvas.draw_workspace(workspace_size=self.defaults['global_workspaceT'])
  3545. def on_workspace(self):
  3546. if self.ui.general_defaults_form.general_app_set_group.workspace_cb.get_value():
  3547. self.plotcanvas.draw_workspace(workspace_size=self.defaults['global_workspaceT'])
  3548. self.inform[str, bool].emit(_("Workspace enabled."), False)
  3549. else:
  3550. self.plotcanvas.delete_workspace()
  3551. self.inform[str, bool].emit(_("Workspace disabled."), False)
  3552. self.preferencesUiManager.defaults_read_form()
  3553. # self.save_defaults(silent=True)
  3554. def on_workspace_toggle(self):
  3555. state = False if self.ui.general_defaults_form.general_app_set_group.workspace_cb.get_value() else True
  3556. try:
  3557. self.ui.general_defaults_form.general_app_set_group.workspace_cb.stateChanged.disconnect(self.on_workspace)
  3558. except TypeError:
  3559. pass
  3560. self.ui.general_defaults_form.general_app_set_group.workspace_cb.set_value(state)
  3561. self.ui.general_defaults_form.general_app_set_group.workspace_cb.stateChanged.connect(self.on_workspace)
  3562. self.on_workspace()
  3563. def on_cursor_type(self, val):
  3564. """
  3565. :param val: type of mouse cursor, set in Preferences ('small' or 'big')
  3566. :return: None
  3567. """
  3568. self.app_cursor.enabled = False
  3569. if val == 'small':
  3570. self.ui.general_defaults_form.general_app_set_group.cursor_size_entry.setDisabled(False)
  3571. self.ui.general_defaults_form.general_app_set_group.cursor_size_lbl.setDisabled(False)
  3572. self.app_cursor = self.plotcanvas.new_cursor()
  3573. else:
  3574. self.ui.general_defaults_form.general_app_set_group.cursor_size_entry.setDisabled(True)
  3575. self.ui.general_defaults_form.general_app_set_group.cursor_size_lbl.setDisabled(True)
  3576. self.app_cursor = self.plotcanvas.new_cursor(big=True)
  3577. if self.ui.grid_snap_btn.isChecked():
  3578. self.app_cursor.enabled = True
  3579. else:
  3580. self.app_cursor.enabled = False
  3581. def on_tool_add_keypress(self):
  3582. # ## Current application units in Upper Case
  3583. self.units = self.defaults['units'].upper()
  3584. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  3585. # work only if the notebook tab on focus is the properties_tab and only if the object is Geometry
  3586. if notebook_widget_name == 'properties_tab':
  3587. if self.collection.get_active().kind == 'geometry':
  3588. # Tool add works for Geometry only if Advanced is True in Preferences
  3589. if self.defaults["global_app_level"] == 'a':
  3590. tool_add_popup = FCInputDialog(title="New Tool ...",
  3591. text='Enter a Tool Diameter:',
  3592. min=0.0000, max=99.9999, decimals=4)
  3593. tool_add_popup.setWindowIcon(QtGui.QIcon(self.resource_location + '/letter_t_32.png'))
  3594. val, ok = tool_add_popup.get_value()
  3595. if ok:
  3596. if float(val) == 0:
  3597. self.inform.emit('[WARNING_NOTCL] %s' %
  3598. _("Please enter a tool diameter with non-zero value, in Float format."))
  3599. return
  3600. self.collection.get_active().on_tool_add(dia=float(val))
  3601. else:
  3602. self.inform.emit('[WARNING_NOTCL] %s...' % _("Adding Tool cancelled"))
  3603. else:
  3604. msgbox = QtWidgets.QMessageBox()
  3605. msgbox.setText(_("Adding Tool works only when Advanced is checked.\n"
  3606. "Go to Preferences -> General - Show Advanced Options."))
  3607. msgbox.setWindowTitle("Tool adding ...")
  3608. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/warning.png'))
  3609. msgbox.setIcon(QtWidgets.QMessageBox.Warning)
  3610. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  3611. msgbox.setDefaultButton(bt_ok)
  3612. msgbox.exec_()
  3613. # work only if the notebook tab on focus is the Tools_Tab
  3614. if notebook_widget_name == 'tool_tab':
  3615. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  3616. # and only if the tool is NCC Tool
  3617. if tool_widget == self.ncclear_tool.toolName:
  3618. self.ncclear_tool.on_add_tool_by_key()
  3619. # and only if the tool is Paint Area Tool
  3620. elif tool_widget == self.paint_tool.toolName:
  3621. self.paint_tool.on_add_tool_by_key()
  3622. # and only if the tool is Solder Paste Dispensing Tool
  3623. elif tool_widget == self.paste_tool.toolName:
  3624. self.paste_tool.on_add_tool_by_key()
  3625. # It's meant to delete tools in tool tables via a 'Delete' shortcut key but only if certain conditions are met
  3626. # See description below.
  3627. def on_delete_keypress(self):
  3628. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  3629. # work only if the notebook tab on focus is the properties_tab and only if the object is Geometry
  3630. if notebook_widget_name == 'properties_tab':
  3631. if str(type(self.collection.get_active())) == "<class 'FlatCAMObj.GeometryObject'>":
  3632. self.collection.get_active().on_tool_delete()
  3633. # work only if the notebook tab on focus is the Tools_Tab
  3634. elif notebook_widget_name == 'tool_tab':
  3635. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  3636. # and only if the tool is NCC Tool
  3637. if tool_widget == self.ncclear_tool.toolName:
  3638. self.ncclear_tool.on_tool_delete()
  3639. # and only if the tool is Paint Tool
  3640. elif tool_widget == self.paint_tool.toolName:
  3641. self.paint_tool.on_tool_delete()
  3642. # and only if the tool is Solder Paste Dispensing Tool
  3643. elif tool_widget == self.paste_tool.toolName:
  3644. self.paste_tool.on_tool_delete()
  3645. # and only if the tool is Isolation Tool
  3646. elif tool_widget == self.isolation_tool.toolName:
  3647. self.isolation_tool.on_tool_delete()
  3648. else:
  3649. self.on_delete()
  3650. # It's meant to delete selected objects. It work also activated by a shortcut key 'Delete' same as above so in
  3651. # some screens you have to be careful where you hover with your mouse.
  3652. # Hovering over Selected tab, if the selected tab is a Geometry it will delete tools in tool table. But even if
  3653. # there is a Selected tab in focus with a Geometry inside, if you hover over canvas it will delete an object.
  3654. # Complicated, I know :)
  3655. def on_delete(self, force_deletion=False):
  3656. """
  3657. Delete the currently selected FlatCAMObjs.
  3658. :param force_deletion: used by Tcl command
  3659. :return: None
  3660. """
  3661. self.defaults.report_usage("on_delete()")
  3662. response = None
  3663. bt_ok = None
  3664. # Make sure that the deletion will happen only after the Editor is no longer active otherwise we might delete
  3665. # a geometry object before we update it.
  3666. if self.geo_editor.editor_active is False and self.exc_editor.editor_active is False \
  3667. and self.grb_editor.editor_active is False and self.gcode_editor.editor_active is False:
  3668. if self.defaults["global_delete_confirmation"] is True and force_deletion is False:
  3669. msgbox = QtWidgets.QMessageBox()
  3670. msgbox.setWindowTitle(_("Delete objects"))
  3671. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/deleteshape32.png'))
  3672. msgbox.setIcon(QtWidgets.QMessageBox.Question)
  3673. # msgbox.setText("<B>%s</B>" % _("Change project units ..."))
  3674. msgbox.setText(_("Are you sure you want to permanently delete\n"
  3675. "the selected objects?"))
  3676. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  3677. msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  3678. msgbox.setDefaultButton(bt_ok)
  3679. msgbox.exec_()
  3680. response = msgbox.clickedButton()
  3681. if self.defaults["global_delete_confirmation"] is False or force_deletion is True:
  3682. response = bt_ok
  3683. if response == bt_ok:
  3684. if self.collection.get_active():
  3685. self.log.debug("App.on_delete()")
  3686. for obj_active in self.collection.get_selected():
  3687. # if the deleted object is GerberObject then make sure to delete the possible mark shapes
  3688. if obj_active.kind == 'gerber':
  3689. obj_active.mark_shapes_storage.clear()
  3690. obj_active.mark_shapes.clear(update=True)
  3691. obj_active.mark_shapes.enabled = False
  3692. elif obj_active.kind == 'cncjob':
  3693. try:
  3694. obj_active.text_col.enabled = False
  3695. del obj_active.text_col
  3696. obj_active.annotation.clear(update=True)
  3697. del obj_active.annotation
  3698. obj_active.probing_shapes.clear(update=True)
  3699. except AttributeError as e:
  3700. log.debug(
  3701. "App.on_delete() --> delete annotations on a FlatCAMCNCJob object. %s" % str(e)
  3702. )
  3703. while self.collection.get_selected():
  3704. self.delete_first_selected()
  3705. # make sure that the selection shape is deleted, too
  3706. self.delete_selection_shape()
  3707. # if there are no longer objects delete also the exclusion areas shapes
  3708. if not self.collection.get_list():
  3709. self.exc_areas.clear_shapes()
  3710. self.inform.emit('%s...' % _("Object(s) deleted"))
  3711. else:
  3712. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. No object(s) selected..."))
  3713. else:
  3714. self.inform.emit(_("Save the work in Editor and try again ..."))
  3715. def delete_first_selected(self):
  3716. # Keep this for later
  3717. try:
  3718. sel_obj = self.collection.get_active()
  3719. name = sel_obj.options["name"]
  3720. isPlotted = sel_obj.options["plot"]
  3721. except AttributeError:
  3722. self.log.debug("Nothing selected for deletion")
  3723. return
  3724. if self.is_legacy is True:
  3725. # Remove plot only if the object was plotted otherwise delaxes will fail
  3726. if isPlotted:
  3727. try:
  3728. # self.plotcanvas.figure.delaxes(self.collection.get_active().axes)
  3729. self.plotcanvas.figure.delaxes(self.collection.get_active().shapes.axes)
  3730. except Exception as e:
  3731. log.debug("App.delete_first_selected() --> %s" % str(e))
  3732. self.plotcanvas.auto_adjust_axes()
  3733. # Remove from dictionary
  3734. self.collection.delete_active()
  3735. # Clear form
  3736. self.setup_default_properties_tab()
  3737. self.inform.emit('%s: %s' % (_("Object deleted"), name))
  3738. def on_set_origin(self):
  3739. """
  3740. Set the origin to the left mouse click position
  3741. :return: None
  3742. """
  3743. # display the message for the user
  3744. # and ask him to click on the desired position
  3745. self.defaults.report_usage("on_set_origin()")
  3746. def origin_replot():
  3747. def worker_task():
  3748. with self.proc_container.new('%s...' % _("Plotting")):
  3749. for obj in self.collection.get_list():
  3750. obj.plot()
  3751. self.plotcanvas.fit_view()
  3752. if self.is_legacy:
  3753. self.plotcanvas.graph_event_disconnect(self.mp_zc)
  3754. else:
  3755. self.plotcanvas.graph_event_disconnect('mouse_press', self.on_set_zero_click)
  3756. self.worker_task.emit({'fcn': worker_task, 'params': []})
  3757. self.inform.emit(_('Click to set the origin ...'))
  3758. self.mp_zc = self.plotcanvas.graph_event_connect('mouse_press', self.on_set_zero_click)
  3759. # first disconnect it as it may have been used by something else
  3760. try:
  3761. self.replot_signal.disconnect()
  3762. except TypeError:
  3763. pass
  3764. self.replot_signal[list].connect(origin_replot)
  3765. def on_set_zero_click(self, event, location=None, noplot=False, use_thread=True):
  3766. """
  3767. :param event:
  3768. :param location:
  3769. :param noplot:
  3770. :param use_thread:
  3771. :return:
  3772. """
  3773. noplot_sig = noplot
  3774. def worker_task():
  3775. with self.proc_container.new(_("Setting Origin...")):
  3776. obj_list = self.collection.get_list()
  3777. for obj in obj_list:
  3778. obj.offset((x, y))
  3779. self.app_obj.object_changed.emit(obj)
  3780. # Update the object bounding box options
  3781. a, b, c, d = obj.bounds()
  3782. obj.options['xmin'] = a
  3783. obj.options['ymin'] = b
  3784. obj.options['xmax'] = c
  3785. obj.options['ymax'] = d
  3786. self.inform.emit('[success] %s...' % _('Origin set'))
  3787. for obj in obj_list:
  3788. out_name = obj.options["name"]
  3789. if obj.kind == 'gerber':
  3790. obj.source_file = self.f_handlers.export_gerber(
  3791. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  3792. elif obj.kind == 'excellon':
  3793. obj.source_file = self.f_handlers.export_excellon(
  3794. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  3795. if noplot_sig is False:
  3796. self.replot_signal.emit([])
  3797. if location is not None:
  3798. if len(location) != 2:
  3799. self.inform.emit('[ERROR_NOTCL] %s...' % _("Origin coordinates specified but incomplete."))
  3800. return 'fail'
  3801. x, y = location
  3802. if use_thread is True:
  3803. self.worker_task.emit({'fcn': worker_task, 'params': []})
  3804. else:
  3805. worker_task()
  3806. self.should_we_save = True
  3807. return
  3808. if event is not None and event.button == 1:
  3809. if self.is_legacy is False:
  3810. event_pos = event.pos
  3811. else:
  3812. event_pos = (event.xdata, event.ydata)
  3813. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  3814. if self.grid_status():
  3815. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  3816. else:
  3817. pos = pos_canvas
  3818. x = 0 - pos[0]
  3819. y = 0 - pos[1]
  3820. if use_thread is True:
  3821. self.worker_task.emit({'fcn': worker_task, 'params': []})
  3822. else:
  3823. worker_task()
  3824. self.should_we_save = True
  3825. def on_move2origin(self, use_thread=True):
  3826. """
  3827. Move selected objects to origin.
  3828. :param use_thread: Control if to use threaded operation. Boolean.
  3829. :return:
  3830. """
  3831. def worker_task():
  3832. with self.proc_container.new(_("Moving to Origin...")):
  3833. obj_list = self.collection.get_selected()
  3834. if not obj_list:
  3835. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. No object(s) selected..."))
  3836. return
  3837. xminlist = []
  3838. yminlist = []
  3839. # first get a bounding box to fit all
  3840. for obj in obj_list:
  3841. xmin, ymin, xmax, ymax = obj.bounds()
  3842. xminlist.append(xmin)
  3843. yminlist.append(ymin)
  3844. # get the minimum x,y for all objects selected
  3845. x = min(xminlist)
  3846. y = min(yminlist)
  3847. for obj in obj_list:
  3848. obj.offset((-x, -y))
  3849. self.app_obj.object_changed.emit(obj)
  3850. # Update the object bounding box options
  3851. a, b, c, d = obj.bounds()
  3852. obj.options['xmin'] = a
  3853. obj.options['ymin'] = b
  3854. obj.options['xmax'] = c
  3855. obj.options['ymax'] = d
  3856. for obj in obj_list:
  3857. obj.plot()
  3858. for obj in obj_list:
  3859. out_name = obj.options["name"]
  3860. if obj.kind == 'gerber':
  3861. obj.source_file = self.f_handlers.export_gerber(
  3862. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  3863. elif obj.kind == 'excellon':
  3864. obj.source_file = self.f_handlers.export_excellon(
  3865. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  3866. self.inform.emit('[success] %s...' % _('Origin set'))
  3867. if use_thread is True:
  3868. self.worker_task.emit({'fcn': worker_task, 'params': []})
  3869. else:
  3870. worker_task()
  3871. self.should_we_save = True
  3872. def on_jump_to(self, custom_location=None, fit_center=True):
  3873. """
  3874. Jump to a location by setting the mouse cursor location.
  3875. :param custom_location: Jump to a specified point. (x, y) tuple.
  3876. :param fit_center: If to fit view. Boolean.
  3877. :return:
  3878. """
  3879. self.defaults.report_usage("on_jump_to()")
  3880. if not custom_location:
  3881. dia_box_location = None
  3882. try:
  3883. dia_box_location = eval(self.clipboard.text())
  3884. except Exception:
  3885. pass
  3886. if type(dia_box_location) == tuple:
  3887. dia_box_location = str(dia_box_location)
  3888. else:
  3889. dia_box_location = None
  3890. # dia_box = Dialog_box(title=_("Jump to ..."),
  3891. # label=_("Enter the coordinates in format X,Y:"),
  3892. # icon=QtGui.QIcon(self.resource_location + '/jump_to16.png'),
  3893. # initial_text=dia_box_location)
  3894. dia_box = DialogBoxRadio(title=_("Jump to ..."),
  3895. label=_("Enter the coordinates in format X,Y:"),
  3896. icon=QtGui.QIcon(self.resource_location + '/jump_to16.png'),
  3897. initial_text=dia_box_location,
  3898. reference=self.defaults['global_jump_ref'])
  3899. if dia_box.ok is True:
  3900. try:
  3901. location = eval(dia_box.location)
  3902. if not isinstance(location, tuple):
  3903. self.inform.emit(_("Wrong coordinates. Enter coordinates in format: X,Y"))
  3904. return
  3905. if dia_box.reference == 'rel':
  3906. rel_x = self.mouse[0] + location[0]
  3907. rel_y = self.mouse[1] + location[1]
  3908. location = (rel_x, rel_y)
  3909. self.defaults['global_jump_ref'] = dia_box.reference
  3910. except Exception:
  3911. return
  3912. else:
  3913. return
  3914. else:
  3915. location = custom_location
  3916. self.jump_signal.emit(location)
  3917. if fit_center:
  3918. self.plotcanvas.fit_center(loc=location)
  3919. cursor = QtGui.QCursor()
  3920. if self.is_legacy is False:
  3921. # I don't know where those differences come from but they are constant for the current
  3922. # execution of the application and they are multiples of a value around 0.0263mm.
  3923. # In a random way sometimes they are more sometimes they are less
  3924. # if units == 'MM':
  3925. # cal_factor = 0.0263
  3926. # else:
  3927. # cal_factor = 0.0263 / 25.4
  3928. cal_location = (location[0], location[1])
  3929. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  3930. jump_loc = self.plotcanvas.translate_coords_2((cal_location[0], cal_location[1]))
  3931. j_pos = (
  3932. int(canvas_origin.x() + round(jump_loc[0])),
  3933. int(canvas_origin.y() + round(jump_loc[1]))
  3934. )
  3935. cursor.setPos(j_pos[0], j_pos[1])
  3936. else:
  3937. # find the canvas origin which is in the top left corner
  3938. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  3939. # determine the coordinates for the lowest left point of the canvas
  3940. x0, y0 = canvas_origin.x(), canvas_origin.y() + self.ui.right_layout.geometry().height()
  3941. # transform the given location from data coordinates to display coordinates. THe display coordinates are
  3942. # in pixels where the origin 0,0 is in the lowest left point of the display window (in our case is the
  3943. # canvas) and the point (width, height) is in the top-right location
  3944. loc = self.plotcanvas.axes.transData.transform_point(location)
  3945. j_pos = (
  3946. int(x0 + loc[0]),
  3947. int(y0 - loc[1])
  3948. )
  3949. cursor.setPos(j_pos[0], j_pos[1])
  3950. self.plotcanvas.mouse = [location[0], location[1]]
  3951. if self.defaults["global_cursor_color_enabled"] is True:
  3952. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1], color=self.cursor_color_3D)
  3953. else:
  3954. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1])
  3955. if self.grid_status():
  3956. # Update cursor
  3957. self.app_cursor.set_data(np.asarray([(location[0], location[1])]),
  3958. symbol='++', edge_color=self.cursor_color_3D,
  3959. edge_width=self.defaults["global_cursor_width"],
  3960. size=self.defaults["global_cursor_size"])
  3961. # Set the relative position label
  3962. dx = location[0] - float(self.rel_point1[0])
  3963. dy = location[1] - float(self.rel_point1[1])
  3964. self.ui.position_label.setText("&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  3965. "<b>Y</b>: %.4f&nbsp;" % (location[0], location[1]))
  3966. # Set the position label
  3967. self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  3968. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (dx, dy))
  3969. units = self.defaults["units"].lower()
  3970. self.plotcanvas.text_hud.text = \
  3971. 'Dx:\t{:<.4f} [{:s}]\nDy:\t{:<.4f} [{:s}]\n\nX: \t{:<.4f} [{:s}]\nY: \t{:<.4f} [{:s}]'.format(
  3972. dx, units, dy, units, location[0], units, location[1], units)
  3973. self.inform.emit('[success] %s' % _("Done."))
  3974. return location
  3975. def on_locate(self, obj, fit_center=True):
  3976. """
  3977. Jump to one of the corners (or center) of an object by setting the mouse cursor location
  3978. :param obj: The object on which to locate certain points
  3979. :param fit_center: If to fit view. Boolean.
  3980. :return: A point location. (x, y) tuple.
  3981. """
  3982. self.defaults.report_usage("on_locate()")
  3983. if obj is None:
  3984. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  3985. return 'fail'
  3986. class DialogBoxChoice(QtWidgets.QDialog):
  3987. def __init__(self, title=None, icon=None, choice='bl'):
  3988. """
  3989. :param title: string with the window title
  3990. """
  3991. super(DialogBoxChoice, self).__init__()
  3992. self.ok = False
  3993. self.setWindowIcon(icon)
  3994. self.setWindowTitle(str(title))
  3995. self.form = QtWidgets.QFormLayout(self)
  3996. self.ref_radio = RadioSet([
  3997. {"label": _("Bottom-Left"), "value": "bl"},
  3998. {"label": _("Top-Left"), "value": "tl"},
  3999. {"label": _("Bottom-Right"), "value": "br"},
  4000. {"label": _("Top-Right"), "value": "tr"},
  4001. {"label": _("Center"), "value": "c"}
  4002. ], orientation='vertical', stretch=False)
  4003. self.ref_radio.set_value(choice)
  4004. self.form.addRow(self.ref_radio)
  4005. self.button_box = QtWidgets.QDialogButtonBox(
  4006. QtWidgets.QDialogButtonBox.Ok | QtWidgets.QDialogButtonBox.Cancel,
  4007. Qt.Horizontal, parent=self)
  4008. self.form.addRow(self.button_box)
  4009. self.button_box.accepted.connect(self.accept)
  4010. self.button_box.rejected.connect(self.reject)
  4011. if self.exec_() == QtWidgets.QDialog.Accepted:
  4012. self.ok = True
  4013. self.location_point = self.ref_radio.get_value()
  4014. else:
  4015. self.ok = False
  4016. self.location_point = None
  4017. dia_box = DialogBoxChoice(title=_("Locate ..."),
  4018. icon=QtGui.QIcon(self.resource_location + '/locate16.png'),
  4019. choice=self.defaults['global_locate_pt'])
  4020. if dia_box.ok is True:
  4021. try:
  4022. location_point = dia_box.location_point
  4023. self.defaults['global_locate_pt'] = dia_box.location_point
  4024. except Exception:
  4025. return
  4026. else:
  4027. return
  4028. loc_b = obj.bounds()
  4029. if location_point == 'bl':
  4030. location = (loc_b[0], loc_b[1])
  4031. elif location_point == 'tl':
  4032. location = (loc_b[0], loc_b[3])
  4033. elif location_point == 'br':
  4034. location = (loc_b[2], loc_b[1])
  4035. elif location_point == 'tr':
  4036. location = (loc_b[2], loc_b[3])
  4037. else:
  4038. # center
  4039. cx = loc_b[0] + ((loc_b[2] - loc_b[0]) / 2)
  4040. cy = loc_b[1] + ((loc_b[3] - loc_b[1]) / 2)
  4041. location = (cx, cy)
  4042. self.locate_signal.emit(location, location_point)
  4043. if fit_center:
  4044. self.plotcanvas.fit_center(loc=location)
  4045. cursor = QtGui.QCursor()
  4046. if self.is_legacy is False:
  4047. # I don't know where those differences come from but they are constant for the current
  4048. # execution of the application and they are multiples of a value around 0.0263mm.
  4049. # In a random way sometimes they are more sometimes they are less
  4050. # if units == 'MM':
  4051. # cal_factor = 0.0263
  4052. # else:
  4053. # cal_factor = 0.0263 / 25.4
  4054. cal_location = (location[0], location[1])
  4055. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  4056. jump_loc = self.plotcanvas.translate_coords_2((cal_location[0], cal_location[1]))
  4057. j_pos = (
  4058. int(canvas_origin.x() + round(jump_loc[0])),
  4059. int(canvas_origin.y() + round(jump_loc[1]))
  4060. )
  4061. cursor.setPos(j_pos[0], j_pos[1])
  4062. else:
  4063. # find the canvas origin which is in the top left corner
  4064. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  4065. # determine the coordinates for the lowest left point of the canvas
  4066. x0, y0 = canvas_origin.x(), canvas_origin.y() + self.ui.right_layout.geometry().height()
  4067. # transform the given location from data coordinates to display coordinates. THe display coordinates are
  4068. # in pixels where the origin 0,0 is in the lowest left point of the display window (in our case is the
  4069. # canvas) and the point (width, height) is in the top-right location
  4070. loc = self.plotcanvas.axes.transData.transform_point(location)
  4071. j_pos = (
  4072. int(x0 + loc[0]),
  4073. int(y0 - loc[1])
  4074. )
  4075. cursor.setPos(j_pos[0], j_pos[1])
  4076. self.plotcanvas.mouse = [location[0], location[1]]
  4077. if self.defaults["global_cursor_color_enabled"] is True:
  4078. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1], color=self.cursor_color_3D)
  4079. else:
  4080. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1])
  4081. if self.grid_status():
  4082. # Update cursor
  4083. self.app_cursor.set_data(np.asarray([(location[0], location[1])]),
  4084. symbol='++', edge_color=self.cursor_color_3D,
  4085. edge_width=self.defaults["global_cursor_width"],
  4086. size=self.defaults["global_cursor_size"])
  4087. # Set the relative position label
  4088. self.dx = location[0] - float(self.rel_point1[0])
  4089. self.dy = location[1] - float(self.rel_point1[1])
  4090. # Set the position label
  4091. self.ui.position_label.setText("&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  4092. "<b>Y</b>: %.4f&nbsp;" % (location[0], location[1]))
  4093. self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  4094. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (self.dx, self.dy))
  4095. units = self.defaults["units"].lower()
  4096. self.plotcanvas.text_hud.text = \
  4097. 'Dx:\t{:<.4f} [{:s}]\nDy:\t{:<.4f} [{:s}]\n\nX: \t{:<.4f} [{:s}]\nY: \t{:<.4f} [{:s}]'.format(
  4098. self.dx, units, self.dy, units, location[0], units, location[1], units)
  4099. self.inform.emit('[success] %s' % _("Done."))
  4100. return location
  4101. def on_copy_command(self):
  4102. """
  4103. Will copy a selection of objects, creating new objects.
  4104. :return:
  4105. """
  4106. self.defaults.report_usage("on_copy_command()")
  4107. def initialize(obj_init, app):
  4108. """
  4109. :param obj_init: the new object
  4110. :type obj_init: class
  4111. :param app: An instance of the App class
  4112. :type app: App
  4113. :return: None
  4114. :rtype:
  4115. """
  4116. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  4117. try:
  4118. obj_init.follow_geometry = deepcopy(obj.follow_geometry)
  4119. except AttributeError:
  4120. pass
  4121. try:
  4122. obj_init.apertures = deepcopy(obj.apertures)
  4123. except AttributeError:
  4124. pass
  4125. try:
  4126. if obj.tools:
  4127. obj_init.tools = deepcopy(obj.tools)
  4128. except Exception as err:
  4129. log.debug("App.on_copy_command() --> %s" % str(err))
  4130. try:
  4131. obj_init.source_file = deepcopy(obj.source_file)
  4132. except (AttributeError, TypeError):
  4133. pass
  4134. def initialize_excellon(obj_init, app):
  4135. obj_init.source_file = deepcopy(obj.source_file)
  4136. obj_init.tools = deepcopy(obj.tools)
  4137. # drills are offset, so they need to be deep copied
  4138. obj_init.drills = deepcopy(obj.drills)
  4139. # slots are offset, so they need to be deep copied
  4140. obj_init.slots = deepcopy(obj.slots)
  4141. obj_init.create_geometry()
  4142. def initialize_script(obj_init, app_obj):
  4143. obj_init.source_file = deepcopy(obj.source_file)
  4144. def initialize_document(obj_init, app_obj):
  4145. obj_init.source_file = deepcopy(obj.source_file)
  4146. for obj in self.collection.get_selected():
  4147. obj_name = obj.options["name"]
  4148. try:
  4149. if isinstance(obj, ExcellonObject):
  4150. self.app_obj.new_object("excellon", str(obj_name) + "_copy", initialize_excellon)
  4151. elif isinstance(obj, GerberObject):
  4152. self.app_obj.new_object("gerber", str(obj_name) + "_copy", initialize)
  4153. elif isinstance(obj, GeometryObject):
  4154. self.app_obj.new_object("geometry", str(obj_name) + "_copy", initialize)
  4155. elif isinstance(obj, ScriptObject):
  4156. self.app_obj.new_object("script", str(obj_name) + "_copy", initialize_script)
  4157. elif isinstance(obj, DocumentObject):
  4158. self.app_obj.new_object("document", str(obj_name) + "_copy", initialize_document)
  4159. except Exception as e:
  4160. return "Operation failed: %s" % str(e)
  4161. def on_copy_object2(self, custom_name):
  4162. def initialize_geometry(obj_init, app):
  4163. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  4164. try:
  4165. obj_init.follow_geometry = deepcopy(obj.follow_geometry)
  4166. except AttributeError:
  4167. pass
  4168. try:
  4169. obj_init.apertures = deepcopy(obj.apertures)
  4170. except AttributeError:
  4171. pass
  4172. try:
  4173. if obj.tools:
  4174. obj_init.tools = deepcopy(obj.tools)
  4175. except Exception as ee:
  4176. log.debug("on_copy_object2() --> %s" % str(ee))
  4177. def initialize_gerber(obj_init, app):
  4178. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  4179. obj_init.apertures = deepcopy(obj.apertures)
  4180. obj_init.aperture_macros = deepcopy(obj.aperture_macros)
  4181. def initialize_excellon(obj_init, app):
  4182. obj_init.tools = deepcopy(obj.tools)
  4183. # drills are offset, so they need to be deep copied
  4184. obj_init.drills = deepcopy(obj.drills)
  4185. # slots are offset, so they need to be deep copied
  4186. obj_init.slots = deepcopy(obj.slots)
  4187. obj_init.create_geometry()
  4188. for obj in self.collection.get_selected():
  4189. obj_name = obj.options["name"]
  4190. try:
  4191. if isinstance(obj, ExcellonObject):
  4192. self.app_obj.new_object("excellon", str(obj_name) + custom_name, initialize_excellon)
  4193. elif isinstance(obj, GerberObject):
  4194. self.app_obj.new_object("gerber", str(obj_name) + custom_name, initialize_gerber)
  4195. elif isinstance(obj, GeometryObject):
  4196. self.app_obj.new_object("geometry", str(obj_name) + custom_name, initialize_geometry)
  4197. except Exception as er:
  4198. return "Operation failed: %s" % str(er)
  4199. def on_rename_object(self, text):
  4200. """
  4201. Will rename an object.
  4202. :param text: New name for the object.
  4203. :return:
  4204. """
  4205. self.defaults.report_usage("on_rename_object()")
  4206. named_obj = self.collection.get_active()
  4207. for obj in named_obj:
  4208. if obj is list:
  4209. self.on_rename_object(text)
  4210. else:
  4211. try:
  4212. obj.options['name'] = text
  4213. except Exception as e:
  4214. log.warning("App.on_rename_object() --> Could not rename the object in the list. --> %s" % str(e))
  4215. def convert_any2geo(self):
  4216. """
  4217. Will convert any object out of Gerber, Excellon, Geometry to Geometry object.
  4218. :return:
  4219. """
  4220. self.defaults.report_usage("convert_any2geo()")
  4221. def initialize(obj_init, app):
  4222. obj_init.solid_geometry = obj.solid_geometry
  4223. try:
  4224. obj_init.follow_geometry = obj.follow_geometry
  4225. except AttributeError:
  4226. pass
  4227. try:
  4228. obj_init.apertures = obj.apertures
  4229. except AttributeError:
  4230. pass
  4231. try:
  4232. if obj.tools:
  4233. obj_init.tools = obj.tools
  4234. except AttributeError:
  4235. pass
  4236. def initialize_excellon(obj_init, app):
  4237. # objs = self.collection.get_selected()
  4238. # GeometryObject.merge(objs, obj)
  4239. solid_geo = []
  4240. for tool in obj.tools:
  4241. for geo in obj.tools[tool]['solid_geometry']:
  4242. solid_geo.append(geo)
  4243. obj_init.solid_geometry = deepcopy(solid_geo)
  4244. if not self.collection.get_selected():
  4245. log.warning("App.convert_any2geo --> No object selected")
  4246. self.inform.emit('[WARNING_NOTCL] %s' %
  4247. _("No object is selected. Select an object and try again."))
  4248. return
  4249. for obj in self.collection.get_selected():
  4250. obj_name = obj.options["name"]
  4251. try:
  4252. if obj.kind == 'excellon':
  4253. self.app_obj.new_object("geometry", str(obj_name) + "_conv", initialize_excellon)
  4254. else:
  4255. self.app_obj.new_object("geometry", str(obj_name) + "_conv", initialize)
  4256. except Exception as e:
  4257. return "Operation failed: %s" % str(e)
  4258. def convert_any2gerber(self):
  4259. """
  4260. Will convert any object out of Gerber, Excellon, Geometry to Gerber object.
  4261. :return:
  4262. """
  4263. def initialize_geometry(obj_init, app):
  4264. apertures = {}
  4265. apid = 0
  4266. apertures[str(apid)] = {}
  4267. apertures[str(apid)]['geometry'] = []
  4268. for obj_orig in obj.solid_geometry:
  4269. new_elem = {}
  4270. new_elem['solid'] = obj_orig
  4271. try:
  4272. new_elem['follow'] = obj_orig.exterior
  4273. except AttributeError:
  4274. pass
  4275. apertures[str(apid)]['geometry'].append(deepcopy(new_elem))
  4276. apertures[str(apid)]['size'] = 0.0
  4277. apertures[str(apid)]['type'] = 'C'
  4278. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  4279. obj_init.apertures = deepcopy(apertures)
  4280. def initialize_excellon(obj_init, app):
  4281. apertures = {}
  4282. apid = 10
  4283. for tool in obj.tools:
  4284. apertures[str(apid)] = {}
  4285. apertures[str(apid)]['geometry'] = []
  4286. for geo in obj.tools[tool]['solid_geometry']:
  4287. new_el = {}
  4288. new_el['solid'] = geo
  4289. new_el['follow'] = geo.exterior
  4290. apertures[str(apid)]['geometry'].append(deepcopy(new_el))
  4291. apertures[str(apid)]['size'] = float(obj.tools[tool]['C'])
  4292. apertures[str(apid)]['type'] = 'C'
  4293. apid += 1
  4294. # create solid_geometry
  4295. solid_geometry = []
  4296. for apid in apertures:
  4297. for geo_el in apertures[apid]['geometry']:
  4298. solid_geometry.append(geo_el['solid'])
  4299. solid_geometry = MultiPolygon(solid_geometry)
  4300. solid_geometry = solid_geometry.buffer(0.0000001)
  4301. obj_init.solid_geometry = deepcopy(solid_geometry)
  4302. obj_init.apertures = deepcopy(apertures)
  4303. # clear the working objects (perhaps not necessary due of Python GC)
  4304. apertures.clear()
  4305. if not self.collection.get_selected():
  4306. log.warning("App.convert_any2gerber --> No object selected")
  4307. self.inform.emit('[WARNING_NOTCL] %s' %
  4308. _("No object is selected. Select an object and try again."))
  4309. return
  4310. for obj in self.collection.get_selected():
  4311. obj_name = obj.options["name"]
  4312. try:
  4313. if obj.kind == 'excellon':
  4314. self.app_obj.new_object("gerber", str(obj_name) + "_conv", initialize_excellon)
  4315. elif obj.kind == 'geometry':
  4316. self.app_obj.new_object("gerber", str(obj_name) + "_conv", initialize_geometry)
  4317. else:
  4318. log.warning("App.convert_any2gerber --> This is no valid object for conversion.")
  4319. except Exception as e:
  4320. return "Operation failed: %s" % str(e)
  4321. def convert_any2excellon(self):
  4322. """
  4323. Will convert any object out of Gerber, Excellon, Geometry to an Excellon object.
  4324. :return:
  4325. """
  4326. def initialize_geometry(obj_init, app):
  4327. tools = {}
  4328. tooluid = 1
  4329. obj_init.solid_geometry = []
  4330. for geo in obj.solid_geometry:
  4331. if not isinstance(geo, (Polygon, MultiPolygon, LinearRing)):
  4332. continue
  4333. minx, miny, maxx, maxy = geo.bounds
  4334. new_dia = min([maxx-minx, maxy-miny])
  4335. new_drill = geo.centroid
  4336. new_drill_geo = new_drill.buffer(new_dia / 2.0)
  4337. current_tooldias = []
  4338. if tools:
  4339. for tool in tools:
  4340. if tools[tool] and 'tooldia' in tools[tool]:
  4341. current_tooldias.append(tools[tool]['tooldia'])
  4342. if new_dia in current_tooldias:
  4343. for tool in tools:
  4344. if float('%.*f' % (self.decimals, tools[tool]["tooldia"])) == float('%.*f' % (self.decimals,
  4345. new_dia)):
  4346. tools[tool]['drills'].append(new_drill)
  4347. tools[tool]['solid_geometry'].append(deepcopy(new_drill_geo))
  4348. else:
  4349. tools[tooluid] = {}
  4350. tools[tooluid]['tooldia'] = new_dia
  4351. tools[tooluid]['drills'] = [new_drill]
  4352. tools[tooluid]['slots'] = []
  4353. tools[tooluid]['solid_geometry'] = [new_drill_geo]
  4354. tooluid += 1
  4355. try:
  4356. obj_init.solid_geometry.append(new_drill_geo)
  4357. except (TypeError, AttributeError):
  4358. obj_init.solid_geometry = [new_drill_geo]
  4359. obj_init.tools = deepcopy(tools)
  4360. obj_init.solid_geometry = unary_union(obj_init.solid_geometry)
  4361. def initialize_gerber(obj_init, app):
  4362. tools = {}
  4363. tooluid = 1
  4364. obj_init.solid_geometry = []
  4365. for apid in obj.apertures:
  4366. if 'geometry' in obj.apertures[apid]:
  4367. for geo_dict in obj.apertures[apid]['geometry']:
  4368. if 'follow' in geo_dict:
  4369. if isinstance(geo_dict['follow'], Point):
  4370. geo = geo_dict['solid']
  4371. minx, miny, maxx, maxy = geo.bounds
  4372. new_dia = min([maxx - minx, maxy - miny])
  4373. new_drill = geo.centroid
  4374. new_drill_geo = new_drill.buffer(new_dia / 2.0)
  4375. current_tooldias = []
  4376. if tools:
  4377. for tool in tools:
  4378. if tools[tool] and 'tooldia' in tools[tool]:
  4379. current_tooldias.append(
  4380. float('%.*f' % (self.decimals, tools[tool]['tooldia']))
  4381. )
  4382. if float('%.*f' % (self.decimals, new_dia)) in current_tooldias:
  4383. for tool in tools:
  4384. if float('%.*f' % (self.decimals, tools[tool]["tooldia"])) == float(
  4385. '%.*f' % (self.decimals, new_dia)):
  4386. if new_drill not in tools[tool]['drills']:
  4387. tools[tool]['drills'].append(new_drill)
  4388. tools[tool]['solid_geometry'].append(deepcopy(new_drill_geo))
  4389. else:
  4390. tools[tooluid] = {}
  4391. tools[tooluid]['tooldia'] = new_dia
  4392. tools[tooluid]['drills'] = [new_drill]
  4393. tools[tooluid]['slots'] = []
  4394. tools[tooluid]['solid_geometry'] = [new_drill_geo]
  4395. tooluid += 1
  4396. try:
  4397. obj_init.solid_geometry.append(new_drill_geo)
  4398. except (TypeError, AttributeError):
  4399. obj_init.solid_geometry = [new_drill_geo]
  4400. elif isinstance(geo_dict['follow'], LineString):
  4401. geo_coords = list(geo_dict['follow'].coords)
  4402. # slots can have only a start and stop point and no intermediate points
  4403. if len(geo_coords) != 2:
  4404. continue
  4405. geo = geo_dict['solid']
  4406. try:
  4407. new_dia = obj.apertures[apid]['size']
  4408. except Exception:
  4409. continue
  4410. new_slot = (Point(geo_coords[0]), Point(geo_coords[1]))
  4411. new_slot_geo = geo
  4412. current_tooldias = []
  4413. if tools:
  4414. for tool in tools:
  4415. if tools[tool] and 'tooldia' in tools[tool]:
  4416. current_tooldias.append(
  4417. float('%.*f' % (self.decimals, tools[tool]['tooldia']))
  4418. )
  4419. if float('%.*f' % (self.decimals, new_dia)) in current_tooldias:
  4420. for tool in tools:
  4421. if float('%.*f' % (self.decimals, tools[tool]["tooldia"])) == float(
  4422. '%.*f' % (self.decimals, new_dia)):
  4423. if new_slot not in tools[tool]['slots']:
  4424. tools[tool]['slots'].append(new_slot)
  4425. tools[tool]['solid_geometry'].append(deepcopy(new_slot_geo))
  4426. else:
  4427. tools[tooluid] = {}
  4428. tools[tooluid]['tooldia'] = new_dia
  4429. tools[tooluid]['drills'] = []
  4430. tools[tooluid]['slots'] = [new_slot]
  4431. tools[tooluid]['solid_geometry'] = [new_slot_geo]
  4432. tooluid += 1
  4433. try:
  4434. obj_init.solid_geometry.append(new_slot_geo)
  4435. except (TypeError, AttributeError):
  4436. obj_init.solid_geometry = [new_slot_geo]
  4437. obj_init.tools = deepcopy(tools)
  4438. obj_init.solid_geometry = unary_union(obj_init.solid_geometry)
  4439. if not self.collection.get_selected():
  4440. log.warning("App.convert_any2excellon--> No object selected")
  4441. self.inform.emit('[WARNING_NOTCL] %s' % _("No object is selected. Select an object and try again."))
  4442. return
  4443. for obj in self.collection.get_selected():
  4444. obj_name = obj.options["name"]
  4445. try:
  4446. if obj.kind == 'gerber':
  4447. self.app_obj.new_object("excellon", str(obj_name) + "_conv", initialize_gerber)
  4448. elif obj.kind == 'geometry':
  4449. self.app_obj.new_object("excellon", str(obj_name) + "_conv", initialize_geometry)
  4450. else:
  4451. log.warning("App.convert_any2excellon --> This is no valid object for conversion.")
  4452. except Exception as e:
  4453. return "Operation failed: %s" % str(e)
  4454. def abort_all_tasks(self):
  4455. """
  4456. Executed when a certain key combo is pressed (Ctrl+Alt+X). Will abort current task
  4457. on the first possible occasion.
  4458. :return:
  4459. """
  4460. if self.abort_flag is False:
  4461. self.inform.emit(_("Aborting. The current task will be gracefully closed as soon as possible..."))
  4462. self.abort_flag = True
  4463. self.cleanup.emit()
  4464. def app_is_idle(self):
  4465. if self.abort_flag:
  4466. self.inform.emit('[WARNING_NOTCL] %s' % _("The current task was gracefully closed on user request..."))
  4467. self.abort_flag = False
  4468. def on_selectall(self):
  4469. """
  4470. Will draw a selection box shape around the selected objects.
  4471. :return:
  4472. """
  4473. self.defaults.report_usage("on_selectall()")
  4474. # delete the possible selection box around a possible selected object
  4475. self.delete_selection_shape()
  4476. for name in self.collection.get_names():
  4477. self.collection.set_active(name)
  4478. curr_sel_obj = self.collection.get_by_name(name)
  4479. # create the selection box around the selected object
  4480. if self.defaults['global_selection_shape'] is True:
  4481. self.draw_selection_shape(curr_sel_obj)
  4482. def on_toggle_preferences(self):
  4483. pref_open = False
  4484. for idx in range(self.ui.plot_tab_area.count()):
  4485. if self.ui.plot_tab_area.tabText(idx) == _("Preferences"):
  4486. pref_open = True
  4487. if pref_open:
  4488. for idx in range(self.ui.plot_tab_area.count()):
  4489. if self.ui.plot_tab_area.tabText(idx) == _("Preferences"):
  4490. self.ui.plot_tab_area.removeTab(idx)
  4491. break
  4492. self.ui.pref_status_label.setStyleSheet("")
  4493. else:
  4494. self.on_preferences()
  4495. def on_preferences(self):
  4496. """
  4497. Adds the Preferences in a Tab in Plot Area
  4498. :return:
  4499. """
  4500. # add the tab if it was closed
  4501. self.ui.plot_tab_area.addTab(self.ui.preferences_tab, _("Preferences"))
  4502. # delete the absolute and relative position and messages in the infobar
  4503. # self.ui.position_label.setText("")
  4504. # self.ui.rel_position_label.setText("")
  4505. # hide coordinates toolbars in the infobar while in DB
  4506. self.ui.coords_toolbar.hide()
  4507. self.ui.delta_coords_toolbar.hide()
  4508. # Switch plot_area to preferences page
  4509. self.ui.plot_tab_area.setCurrentWidget(self.ui.preferences_tab)
  4510. # self.ui.show()
  4511. self.ui.pref_status_label.setStyleSheet("""
  4512. QLabel
  4513. {
  4514. color: black;
  4515. background-color: lightseagreen;
  4516. }
  4517. """
  4518. )
  4519. # detect changes in the preferences
  4520. for idx in range(self.ui.pref_tab_area.count()):
  4521. for tb in self.ui.pref_tab_area.widget(idx).findChildren(QtCore.QObject):
  4522. try:
  4523. try:
  4524. tb.textEdited.disconnect(self.preferencesUiManager.on_preferences_edited)
  4525. except (TypeError, AttributeError):
  4526. pass
  4527. tb.textEdited.connect(self.preferencesUiManager.on_preferences_edited)
  4528. except AttributeError:
  4529. pass
  4530. try:
  4531. try:
  4532. tb.modificationChanged.disconnect(self.preferencesUiManager.on_preferences_edited)
  4533. except (TypeError, AttributeError):
  4534. pass
  4535. tb.modificationChanged.connect(self.preferencesUiManager.on_preferences_edited)
  4536. except AttributeError:
  4537. pass
  4538. try:
  4539. try:
  4540. tb.toggled.disconnect(self.preferencesUiManager.on_preferences_edited)
  4541. except (TypeError, AttributeError):
  4542. pass
  4543. tb.toggled.connect(self.preferencesUiManager.on_preferences_edited)
  4544. except AttributeError:
  4545. pass
  4546. try:
  4547. try:
  4548. tb.valueChanged.disconnect(self.preferencesUiManager.on_preferences_edited)
  4549. except (TypeError, AttributeError):
  4550. pass
  4551. tb.valueChanged.connect(self.preferencesUiManager.on_preferences_edited)
  4552. except AttributeError:
  4553. pass
  4554. try:
  4555. try:
  4556. tb.currentIndexChanged.disconnect(self.preferencesUiManager.on_preferences_edited)
  4557. except (TypeError, AttributeError):
  4558. pass
  4559. tb.currentIndexChanged.connect(self.preferencesUiManager.on_preferences_edited)
  4560. except AttributeError:
  4561. pass
  4562. def on_tools_database(self, source='app'):
  4563. """
  4564. Adds the Tools Database in a Tab in Plot Area.
  4565. :return:
  4566. """
  4567. for idx in range(self.ui.plot_tab_area.count()):
  4568. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  4569. # there can be only one instance of Tools Database at one time
  4570. return
  4571. if source == 'app':
  4572. self.tools_db_tab = ToolsDB2(
  4573. app=self,
  4574. parent=self.ui,
  4575. callback_on_edited=self.on_tools_db_edited,
  4576. callback_on_tool_request=self.on_geometry_tool_add_from_db_executed
  4577. )
  4578. elif source == 'ncc':
  4579. self.tools_db_tab = ToolsDB2(
  4580. app=self,
  4581. parent=self.ui,
  4582. callback_on_edited=self.on_tools_db_edited,
  4583. callback_on_tool_request=self.ncclear_tool.on_ncc_tool_add_from_db_executed
  4584. )
  4585. elif source == 'paint':
  4586. self.tools_db_tab = ToolsDB2(
  4587. app=self,
  4588. parent=self.ui,
  4589. callback_on_edited=self.on_tools_db_edited,
  4590. callback_on_tool_request=self.paint_tool.on_paint_tool_add_from_db_executed
  4591. )
  4592. elif source == 'iso':
  4593. self.tools_db_tab = ToolsDB2(
  4594. app=self,
  4595. parent=self.ui,
  4596. callback_on_edited=self.on_tools_db_edited,
  4597. callback_on_tool_request=self.isolation_tool.on_iso_tool_add_from_db_executed
  4598. )
  4599. elif source == 'cutout':
  4600. self.tools_db_tab = ToolsDB2(
  4601. app=self,
  4602. parent=self.ui,
  4603. callback_on_edited=self.on_tools_db_edited,
  4604. callback_on_tool_request=self.cutout_tool.on_cutout_tool_add_from_db_executed
  4605. )
  4606. # add the tab if it was closed
  4607. try:
  4608. self.ui.plot_tab_area.addTab(self.tools_db_tab, _("Tools Database"))
  4609. self.tools_db_tab.setObjectName("database_tab")
  4610. except Exception as e:
  4611. log.debug("App.on_tools_database() --> %s" % str(e))
  4612. return
  4613. # delete the absolute and relative position and messages in the infobar
  4614. # self.ui.position_label.setText("")
  4615. # self.ui.rel_position_label.setText("")
  4616. # hide coordinates toolbars in the infobar while in DB
  4617. self.ui.coords_toolbar.hide()
  4618. self.ui.delta_coords_toolbar.hide()
  4619. # Switch plot_area to preferences page
  4620. self.ui.plot_tab_area.setCurrentWidget(self.tools_db_tab)
  4621. # detect changes in the Tools in Tools DB, connect signals from table widget in tab
  4622. self.tools_db_tab.ui_connect()
  4623. def on_tools_db_edited(self):
  4624. """
  4625. Executed whenever a tool is edited in Tools Database.
  4626. Will color the text of the Tools Database tab to Red color.
  4627. :return:
  4628. """
  4629. self.inform[str, bool].emit('[WARNING_NOTCL] %s' % _("Tools in Tools Database edited but not saved."), False)
  4630. for idx in range(self.ui.plot_tab_area.count()):
  4631. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  4632. self.ui.plot_tab_area.tabBar.setTabTextColor(idx, QtGui.QColor('red'))
  4633. self.tools_db_tab.ui.save_db_btn.setStyleSheet("QPushButton {color: red;}")
  4634. self.tools_db_changed_flag = True
  4635. def on_geometry_tool_add_from_db_executed(self, tool):
  4636. """
  4637. Here add the tool from DB in the selected geometry object.
  4638. :return:
  4639. """
  4640. tool_from_db = deepcopy(tool)
  4641. obj = self.collection.get_active()
  4642. if obj.kind == 'geometry':
  4643. obj.on_tool_from_db_inserted(tool=tool_from_db)
  4644. # close the tab and delete it
  4645. for idx in range(self.ui.plot_tab_area.count()):
  4646. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  4647. wdg = self.ui.plot_tab_area.widget(idx)
  4648. wdg.deleteLater()
  4649. self.ui.plot_tab_area.removeTab(idx)
  4650. self.inform.emit('[success] %s' % _("Tool from DB added in Tool Table."))
  4651. elif obj.kind == 'gerber':
  4652. self.isolation_tool.on_tool_from_db_inserted(tool=tool_from_db)
  4653. # close the tab and delete it
  4654. for idx in range(self.ui.plot_tab_area.count()):
  4655. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  4656. wdg = self.ui.plot_tab_area.widget(idx)
  4657. wdg.deleteLater()
  4658. self.ui.plot_tab_area.removeTab(idx)
  4659. self.inform.emit('[success] %s' % _("Tool from DB added in Tool Table."))
  4660. else:
  4661. self.inform.emit('[ERROR_NOTCL] %s' % _("Adding tool from DB is not allowed for this object."))
  4662. def on_plot_area_tab_closed(self, tab_obj_name):
  4663. """
  4664. Executed whenever a QTab is closed in the Plot Area.
  4665. :param tab_obj_name: The objectName of the Tab that was closed. This objectName is assigned on Tab creation
  4666. :return:
  4667. """
  4668. if tab_obj_name == "preferences_tab":
  4669. self.preferencesUiManager.on_close_preferences_tab()
  4670. elif tab_obj_name == "database_tab":
  4671. # disconnect the signals from the table widget in tab
  4672. self.tools_db_tab.ui_disconnect()
  4673. if self.tools_db_changed_flag is True:
  4674. msgbox = QtWidgets.QMessageBox()
  4675. msgbox.setText(_("One or more Tools are edited.\n"
  4676. "Do you want to update the Tools Database?"))
  4677. msgbox.setWindowTitle(_("Save Tools Database"))
  4678. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  4679. msgbox.setIcon(QtWidgets.QMessageBox.Question)
  4680. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  4681. msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  4682. msgbox.setDefaultButton(bt_yes)
  4683. msgbox.exec_()
  4684. response = msgbox.clickedButton()
  4685. if response == bt_yes:
  4686. self.tools_db_tab.on_save_tools_db()
  4687. self.inform.emit('[success] %s' % "Tools DB saved to file.")
  4688. else:
  4689. self.tools_db_changed_flag = False
  4690. self.inform.emit('')
  4691. return
  4692. self.tools_db_tab.deleteLater()
  4693. elif tab_obj_name == "text_editor_tab":
  4694. self.toggle_codeeditor = False
  4695. elif tab_obj_name == "bookmarks_tab":
  4696. self.book_dialog_tab.rebuild_actions()
  4697. self.book_dialog_tab.deleteLater()
  4698. else:
  4699. pass
  4700. # restore the coords toolbars
  4701. self.ui.toggle_coords(checked=self.defaults["global_coords_show"])
  4702. self.ui.toggle_delta_coords(checked=self.defaults["global_delta_coords_show"])
  4703. def on_flipy(self):
  4704. """
  4705. Executed when the menu entry in Options -> Flip on Y axis is clicked.
  4706. :return:
  4707. """
  4708. self.defaults.report_usage("on_flipy()")
  4709. obj_list = self.collection.get_selected()
  4710. xminlist = []
  4711. yminlist = []
  4712. xmaxlist = []
  4713. ymaxlist = []
  4714. if not obj_list:
  4715. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected to Flip on Y axis."))
  4716. else:
  4717. try:
  4718. # first get a bounding box to fit all
  4719. for obj in obj_list:
  4720. xmin, ymin, xmax, ymax = obj.bounds()
  4721. xminlist.append(xmin)
  4722. yminlist.append(ymin)
  4723. xmaxlist.append(xmax)
  4724. ymaxlist.append(ymax)
  4725. # get the minimum x,y and maximum x,y for all objects selected
  4726. xminimal = min(xminlist)
  4727. yminimal = min(yminlist)
  4728. xmaximal = max(xmaxlist)
  4729. ymaximal = max(ymaxlist)
  4730. px = 0.5 * (xminimal + xmaximal)
  4731. py = 0.5 * (yminimal + ymaximal)
  4732. # execute mirroring
  4733. for obj in obj_list:
  4734. obj.mirror('X', [px, py])
  4735. obj.plot()
  4736. self.app_obj.object_changed.emit(obj)
  4737. self.inform.emit('[success] %s' %
  4738. _("Flip on Y axis done."))
  4739. except Exception as e:
  4740. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Flip action was not executed."), str(e)))
  4741. return
  4742. def on_flipx(self):
  4743. """
  4744. Executed when the menu entry in Options -> Flip on X axis is clicked.
  4745. :return:
  4746. """
  4747. self.defaults.report_usage("on_flipx()")
  4748. obj_list = self.collection.get_selected()
  4749. xminlist = []
  4750. yminlist = []
  4751. xmaxlist = []
  4752. ymaxlist = []
  4753. if not obj_list:
  4754. self.inform.emit('[WARNING_NOTCL] %s' %
  4755. _("No object selected to Flip on X axis."))
  4756. else:
  4757. try:
  4758. # first get a bounding box to fit all
  4759. for obj in obj_list:
  4760. xmin, ymin, xmax, ymax = obj.bounds()
  4761. xminlist.append(xmin)
  4762. yminlist.append(ymin)
  4763. xmaxlist.append(xmax)
  4764. ymaxlist.append(ymax)
  4765. # get the minimum x,y and maximum x,y for all objects selected
  4766. xminimal = min(xminlist)
  4767. yminimal = min(yminlist)
  4768. xmaximal = max(xmaxlist)
  4769. ymaximal = max(ymaxlist)
  4770. px = 0.5 * (xminimal + xmaximal)
  4771. py = 0.5 * (yminimal + ymaximal)
  4772. # execute mirroring
  4773. for obj in obj_list:
  4774. obj.mirror('Y', [px, py])
  4775. obj.plot()
  4776. self.app_obj.object_changed.emit(obj)
  4777. self.inform.emit('[success] %s' %
  4778. _("Flip on X axis done."))
  4779. except Exception as e:
  4780. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Flip action was not executed."), str(e)))
  4781. return
  4782. def on_rotate(self, silent=False, preset=None):
  4783. """
  4784. Executed when Options -> Rotate Selection menu entry is clicked.
  4785. :param silent: If silent is True then use the preset value for the angle of the rotation.
  4786. :param preset: A value to be used as predefined angle for rotation.
  4787. :return:
  4788. """
  4789. self.defaults.report_usage("on_rotate()")
  4790. obj_list = self.collection.get_selected()
  4791. xminlist = []
  4792. yminlist = []
  4793. xmaxlist = []
  4794. ymaxlist = []
  4795. if not obj_list:
  4796. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected to Rotate."))
  4797. else:
  4798. if silent is False:
  4799. rotatebox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  4800. min=-360, max=360, decimals=4,
  4801. init_val=float(self.defaults['tools_transform_rotate']))
  4802. num, ok = rotatebox.get_value()
  4803. else:
  4804. num = preset
  4805. ok = True
  4806. if ok:
  4807. try:
  4808. # first get a bounding box to fit all
  4809. for obj in obj_list:
  4810. xmin, ymin, xmax, ymax = obj.bounds()
  4811. xminlist.append(xmin)
  4812. yminlist.append(ymin)
  4813. xmaxlist.append(xmax)
  4814. ymaxlist.append(ymax)
  4815. # get the minimum x,y and maximum x,y for all objects selected
  4816. xminimal = min(xminlist)
  4817. yminimal = min(yminlist)
  4818. xmaximal = max(xmaxlist)
  4819. ymaximal = max(ymaxlist)
  4820. px = 0.5 * (xminimal + xmaximal)
  4821. py = 0.5 * (yminimal + ymaximal)
  4822. for sel_obj in obj_list:
  4823. sel_obj.rotate(-float(num), point=(px, py))
  4824. sel_obj.plot()
  4825. self.app_obj.object_changed.emit(sel_obj)
  4826. self.inform.emit('[success] %s' % _("Rotation done."))
  4827. except Exception as e:
  4828. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Rotation movement was not executed."), str(e)))
  4829. return
  4830. def on_skewx(self):
  4831. """
  4832. Executed when the menu entry in Options -> Skew on X axis is clicked.
  4833. :return:
  4834. """
  4835. self.defaults.report_usage("on_skewx()")
  4836. obj_list = self.collection.get_selected()
  4837. xminlist = []
  4838. yminlist = []
  4839. if not obj_list:
  4840. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected to Skew/Shear on X axis."))
  4841. else:
  4842. skewxbox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  4843. min=-360, max=360, decimals=4,
  4844. init_val=float(self.defaults['tools_transform_skew_x']))
  4845. num, ok = skewxbox.get_value()
  4846. if ok:
  4847. # first get a bounding box to fit all
  4848. for obj in obj_list:
  4849. xmin, ymin, xmax, ymax = obj.bounds()
  4850. xminlist.append(xmin)
  4851. yminlist.append(ymin)
  4852. # get the minimum x,y and maximum x,y for all objects selected
  4853. xminimal = min(xminlist)
  4854. yminimal = min(yminlist)
  4855. for obj in obj_list:
  4856. obj.skew(num, 0, point=(xminimal, yminimal))
  4857. obj.plot()
  4858. self.app_obj.object_changed.emit(obj)
  4859. self.inform.emit('[success] %s' % _("Skew on X axis done."))
  4860. def on_skewy(self):
  4861. """
  4862. Executed when the menu entry in Options -> Skew on Y axis is clicked.
  4863. :return:
  4864. """
  4865. self.defaults.report_usage("on_skewy()")
  4866. obj_list = self.collection.get_selected()
  4867. xminlist = []
  4868. yminlist = []
  4869. if not obj_list:
  4870. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected to Skew/Shear on Y axis."))
  4871. else:
  4872. skewybox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  4873. min=-360, max=360, decimals=4,
  4874. init_val=float(self.defaults['tools_transform_skew_y']))
  4875. num, ok = skewybox.get_value()
  4876. if ok:
  4877. # first get a bounding box to fit all
  4878. for obj in obj_list:
  4879. xmin, ymin, xmax, ymax = obj.bounds()
  4880. xminlist.append(xmin)
  4881. yminlist.append(ymin)
  4882. # get the minimum x,y and maximum x,y for all objects selected
  4883. xminimal = min(xminlist)
  4884. yminimal = min(yminlist)
  4885. for obj in obj_list:
  4886. obj.skew(0, num, point=(xminimal, yminimal))
  4887. obj.plot()
  4888. self.app_obj.object_changed.emit(obj)
  4889. self.inform.emit('[success] %s' % _("Skew on Y axis done."))
  4890. def on_plots_updated(self):
  4891. """
  4892. Callback used to report when the plots have changed.
  4893. Adjust axes and zooms to fit.
  4894. :return: None
  4895. """
  4896. if self.is_legacy is False:
  4897. self.plotcanvas.update()
  4898. else:
  4899. self.plotcanvas.auto_adjust_axes()
  4900. self.on_zoom_fit()
  4901. self.collection.update_view()
  4902. # self.inform.emit(_("Plots updated ..."))
  4903. def on_toolbar_replot(self):
  4904. """
  4905. Callback for toolbar button. Re-plots all objects.
  4906. :return: None
  4907. """
  4908. self.log.debug("on_toolbar_replot()")
  4909. try:
  4910. obj = self.collection.get_active()
  4911. if obj:
  4912. obj.read_form()
  4913. else:
  4914. self.on_zoom_fit()
  4915. except AttributeError as e:
  4916. log.debug("on_toolbar_replot() -> %s" % str(e))
  4917. pass
  4918. self.plot_all()
  4919. def grid_status(self):
  4920. return True if self.ui.grid_snap_btn.isChecked() else False
  4921. def populate_cmenu_grids(self):
  4922. units = self.defaults['units'].lower()
  4923. # for act in self.ui.cmenu_gridmenu.actions():
  4924. # act.triggered.disconnect()
  4925. self.ui.cmenu_gridmenu.clear()
  4926. sorted_list = sorted(self.defaults["global_grid_context_menu"][str(units)])
  4927. grid_toggle = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/grid32_menu.png'),
  4928. _("Grid On/Off"))
  4929. grid_toggle.setCheckable(True)
  4930. grid_toggle.setChecked(True) if self.grid_status() else grid_toggle.setChecked(False)
  4931. self.ui.cmenu_gridmenu.addSeparator()
  4932. for grid in sorted_list:
  4933. action = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/grid32_menu.png'),
  4934. "%s" % str(grid))
  4935. action.triggered.connect(self.set_grid)
  4936. self.ui.cmenu_gridmenu.addSeparator()
  4937. grid_add = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/plus32.png'),
  4938. _("Add"))
  4939. grid_delete = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/delete32.png'),
  4940. _("Delete"))
  4941. grid_add.triggered.connect(self.on_grid_add)
  4942. grid_delete.triggered.connect(self.on_grid_delete)
  4943. grid_toggle.triggered.connect(lambda: self.ui.grid_snap_btn.trigger())
  4944. def set_grid(self):
  4945. menu_action = self.sender()
  4946. assert isinstance(menu_action, QtWidgets.QAction), "Expected QAction got %s" % type(menu_action)
  4947. self.ui.grid_gap_x_entry.setText(menu_action.text())
  4948. self.ui.grid_gap_y_entry.setText(menu_action.text())
  4949. def on_grid_add(self):
  4950. # ## Current application units in lower Case
  4951. units = self.defaults['units'].lower()
  4952. grid_add_popup = FCInputDialog(title=_("New Grid ..."),
  4953. text=_('Enter a Grid Value:'),
  4954. min=0.0000, max=99.9999, decimals=4)
  4955. grid_add_popup.setWindowIcon(QtGui.QIcon(self.resource_location + '/plus32.png'))
  4956. val, ok = grid_add_popup.get_value()
  4957. if ok:
  4958. if float(val) == 0:
  4959. self.inform.emit('[WARNING_NOTCL] %s' %
  4960. _("Please enter a grid value with non-zero value, in Float format."))
  4961. return
  4962. else:
  4963. if val not in self.defaults["global_grid_context_menu"][str(units)]:
  4964. self.defaults["global_grid_context_menu"][str(units)].append(val)
  4965. self.inform.emit('[success] %s...' % _("New Grid added"))
  4966. else:
  4967. self.inform.emit('[WARNING_NOTCL] %s...' % _("Grid already exists"))
  4968. else:
  4969. self.inform.emit('[WARNING_NOTCL] %s...' % _("Adding New Grid cancelled"))
  4970. def on_grid_delete(self):
  4971. # ## Current application units in lower Case
  4972. units = self.defaults['units'].lower()
  4973. grid_del_popup = FCInputDialog(title="Delete Grid ...",
  4974. text='Enter a Grid Value:',
  4975. min=0.0000, max=99.9999, decimals=4)
  4976. grid_del_popup.setWindowIcon(QtGui.QIcon(self.resource_location + '/delete32.png'))
  4977. val, ok = grid_del_popup.get_value()
  4978. if ok:
  4979. if float(val) == 0:
  4980. self.inform.emit('[WARNING_NOTCL] %s' %
  4981. _("Please enter a grid value with non-zero value, in Float format."))
  4982. return
  4983. else:
  4984. try:
  4985. self.defaults["global_grid_context_menu"][str(units)].remove(val)
  4986. except ValueError:
  4987. self.inform.emit('[ERROR_NOTCL]%s...' % _(" Grid Value does not exist"))
  4988. return
  4989. self.inform.emit('[success] %s...' % _("Grid Value deleted"))
  4990. else:
  4991. self.inform.emit('[WARNING_NOTCL] %s...' % _("Delete Grid value cancelled"))
  4992. def on_shortcut_list(self):
  4993. self.defaults.report_usage("on_shortcut_list()")
  4994. # add the tab if it was closed
  4995. self.ui.plot_tab_area.addTab(self.ui.shortcuts_tab, _("Key Shortcut List"))
  4996. # delete the absolute and relative position and messages in the infobar
  4997. # self.ui.position_label.setText("")
  4998. # self.ui.rel_position_label.setText("")
  4999. # hide coordinates toolbars in the infobar while in DB
  5000. self.ui.coords_toolbar.hide()
  5001. self.ui.delta_coords_toolbar.hide()
  5002. # Switch plot_area to preferences page
  5003. self.ui.plot_tab_area.setCurrentWidget(self.ui.shortcuts_tab)
  5004. # self.ui.show()
  5005. def on_select_tab(self, name):
  5006. # if the splitter is hidden, display it, else hide it but only if the current widget is the same
  5007. if self.ui.splitter.sizes()[0] == 0:
  5008. self.ui.splitter.setSizes([1, 1])
  5009. else:
  5010. if self.ui.notebook.currentWidget().objectName() == name + '_tab':
  5011. self.ui.splitter.setSizes([0, 1])
  5012. if name == 'project':
  5013. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  5014. elif name == 'selected':
  5015. self.ui.notebook.setCurrentWidget(self.ui.properties_tab)
  5016. elif name == 'tool':
  5017. self.ui.notebook.setCurrentWidget(self.ui.tool_tab)
  5018. def on_copy_name(self):
  5019. self.defaults.report_usage("on_copy_name()")
  5020. obj = self.collection.get_active()
  5021. try:
  5022. name = obj.options["name"]
  5023. except AttributeError:
  5024. log.debug("on_copy_name() --> No object selected to copy it's name")
  5025. self.inform.emit('[WARNING_NOTCL] %s' %
  5026. _(" No object selected to copy it's name"))
  5027. return
  5028. self.clipboard.setText(name)
  5029. self.inform.emit(_("Name copied on clipboard ..."))
  5030. def on_mouse_click_over_plot(self, event):
  5031. """
  5032. Default actions are:
  5033. :param event: Contains information about the event, like which button
  5034. was clicked, the pixel coordinates and the axes coordinates.
  5035. :return: None
  5036. """
  5037. self.pos = []
  5038. if self.is_legacy is False:
  5039. event_pos = event.pos
  5040. # pan_button = 2 if self.defaults["global_pan_button"] == '2'else 3
  5041. # # Set the mouse button for panning
  5042. # self.plotcanvas.view.camera.pan_button_setting = pan_button
  5043. else:
  5044. event_pos = (event.xdata, event.ydata)
  5045. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  5046. # pan_button = 3 if self.defaults["global_pan_button"] == '2' else 2
  5047. # So it can receive key presses
  5048. self.plotcanvas.native.setFocus()
  5049. self.pos_canvas = self.plotcanvas.translate_coords(event_pos)
  5050. if self.grid_status():
  5051. self.pos = self.geo_editor.snap(self.pos_canvas[0], self.pos_canvas[1])
  5052. else:
  5053. self.pos = (self.pos_canvas[0], self.pos_canvas[1])
  5054. try:
  5055. if event.button == 1:
  5056. # Reset here the relative coordinates so there is a new reference on the click position
  5057. if self.rel_point1 is None:
  5058. self.rel_point1 = self.pos
  5059. else:
  5060. self.rel_point2 = copy(self.rel_point1)
  5061. self.rel_point1 = self.pos
  5062. self.on_mouse_move_over_plot(event, origin_click=True)
  5063. except Exception as e:
  5064. App.log.debug("App.on_mouse_click_over_plot() --> Outside plot? --> %s" % str(e))
  5065. def on_mouse_double_click_over_plot(self, event):
  5066. if event.button == 1:
  5067. self.doubleclick = True
  5068. def on_mouse_move_over_plot(self, event, origin_click=None):
  5069. """
  5070. Callback for the mouse motion event over the plot.
  5071. :param event: Contains information about the event.
  5072. :param origin_click
  5073. :return: None
  5074. """
  5075. if self.is_legacy is False:
  5076. event_pos = event.pos
  5077. if self.defaults["global_pan_button"] == '2':
  5078. pan_button = 2
  5079. else:
  5080. pan_button = 3
  5081. self.event_is_dragging = event.is_dragging
  5082. else:
  5083. event_pos = (event.xdata, event.ydata)
  5084. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  5085. if self.defaults["global_pan_button"] == '2':
  5086. pan_button = 3
  5087. else:
  5088. pan_button = 2
  5089. self.event_is_dragging = self.plotcanvas.is_dragging
  5090. # So it can receive key presses but not when the Tcl Shell is active
  5091. if not self.ui.shell_dock.isVisible():
  5092. if not self.plotcanvas.native.hasFocus():
  5093. self.plotcanvas.native.setFocus()
  5094. self.pos_jump = event_pos
  5095. self.ui.popMenu.mouse_is_panning = False
  5096. if origin_click is None:
  5097. # if the RMB is clicked and mouse is moving over plot then 'panning_action' is True
  5098. if event.button == pan_button and self.event_is_dragging == 1:
  5099. # if a popup menu is active don't change mouse_is_panning variable because is not True
  5100. if self.ui.popMenu.popup_active:
  5101. self.ui.popMenu.popup_active = False
  5102. return
  5103. self.ui.popMenu.mouse_is_panning = True
  5104. return
  5105. if self.rel_point1 is not None:
  5106. try: # May fail in case mouse not within axes
  5107. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  5108. if pos_canvas[0] is None or pos_canvas[1] is None:
  5109. return
  5110. if self.grid_status():
  5111. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  5112. # Update cursor
  5113. self.app_cursor.set_data(np.asarray([(pos[0], pos[1])]),
  5114. symbol='++', edge_color=self.cursor_color_3D,
  5115. edge_width=self.defaults["global_cursor_width"],
  5116. size=self.defaults["global_cursor_size"])
  5117. else:
  5118. pos = (pos_canvas[0], pos_canvas[1])
  5119. self.dx = pos[0] - float(self.rel_point1[0])
  5120. self.dy = pos[1] - float(self.rel_point1[1])
  5121. self.ui.position_label.setText("&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  5122. "<b>Y</b>: %.4f&nbsp;" % (pos[0], pos[1]))
  5123. self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  5124. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (self.dx, self.dy))
  5125. units = self.defaults["units"].lower()
  5126. self.plotcanvas.text_hud.text = \
  5127. 'Dx:\t{:<.4f} [{:s}]\nDy:\t{:<.4f} [{:s}]\n\nX: \t{:<.4f} [{:s}]\nY: \t{:<.4f} [{:s}]'.format(
  5128. self.dx, units, self.dy, units, pos[0], units, pos[1], units)
  5129. self.mouse = [pos[0], pos[1]]
  5130. if self.defaults['global_selection_shape'] is False:
  5131. self.selection_type = None
  5132. return
  5133. # if the mouse is moved and the LMB is clicked then the action is a selection
  5134. if self.event_is_dragging == 1 and event.button == 1:
  5135. self.delete_selection_shape()
  5136. if self.dx < 0:
  5137. self.draw_moving_selection_shape(self.pos, pos, color=self.defaults['global_alt_sel_line'],
  5138. face_color=self.defaults['global_alt_sel_fill'])
  5139. self.selection_type = False
  5140. elif self.dx >= 0:
  5141. self.draw_moving_selection_shape(self.pos, pos)
  5142. self.selection_type = True
  5143. else:
  5144. self.selection_type = None
  5145. else:
  5146. self.selection_type = None
  5147. # hover effect - enabled in Preferences -> General -> appGUI Settings
  5148. if self.defaults['global_hover']:
  5149. for obj in self.collection.get_list():
  5150. try:
  5151. # select the object(s) only if it is enabled (plotted)
  5152. if obj.options['plot']:
  5153. if obj not in self.collection.get_selected():
  5154. poly_obj = Polygon(
  5155. [(obj.options['xmin'], obj.options['ymin']),
  5156. (obj.options['xmax'], obj.options['ymin']),
  5157. (obj.options['xmax'], obj.options['ymax']),
  5158. (obj.options['xmin'], obj.options['ymax'])]
  5159. )
  5160. if Point(pos).within(poly_obj):
  5161. if obj.isHovering is False:
  5162. obj.isHovering = True
  5163. obj.notHovering = True
  5164. # create the selection box around the selected object
  5165. self.draw_hover_shape(obj, color='#d1e0e0FF')
  5166. else:
  5167. if obj.notHovering is True:
  5168. obj.notHovering = False
  5169. obj.isHovering = False
  5170. self.delete_hover_shape()
  5171. except Exception:
  5172. # the Exception here will happen if we try to select on screen and we have an
  5173. # newly (and empty) just created Geometry or Excellon object that do not have the
  5174. # xmin, xmax, ymin, ymax options.
  5175. # In this case poly_obj creation (see above) will fail
  5176. pass
  5177. except Exception as e:
  5178. log.debug("App.on_mouse_move_over_plot() - rel_point1 is not None -> %s" % str(e))
  5179. self.ui.position_label.setText("")
  5180. self.ui.rel_position_label.setText("")
  5181. self.mouse = None
  5182. def on_mouse_click_release_over_plot(self, event):
  5183. """
  5184. Callback for the mouse click release over plot. This event is generated by the Matplotlib backend
  5185. and has been registered in ''self.__init__()''.
  5186. :param event: contains information about the event.
  5187. :return:
  5188. """
  5189. if self.is_legacy is False:
  5190. event_pos = event.pos
  5191. right_button = 2
  5192. else:
  5193. event_pos = (event.xdata, event.ydata)
  5194. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  5195. right_button = 3
  5196. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  5197. if self.grid_status():
  5198. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  5199. else:
  5200. pos = (pos_canvas[0], pos_canvas[1])
  5201. # if the released mouse button was RMB then test if it was a panning motion or not, if not it was a context
  5202. # canvas menu
  5203. if event.button == right_button and self.ui.popMenu.mouse_is_panning is False: # right click
  5204. self.ui.popMenu.mouse_is_panning = False
  5205. self.cursor = QtGui.QCursor()
  5206. self.populate_cmenu_grids()
  5207. self.ui.popMenu.popup(self.cursor.pos())
  5208. # if the released mouse button was LMB then test if we had a right-to-left selection or a left-to-right
  5209. # selection and then select a type of selection ("enclosing" or "touching")
  5210. if event.button == 1: # left click
  5211. modifiers = QtWidgets.QApplication.keyboardModifiers()
  5212. # If the SHIFT key is pressed when LMB is clicked then the coordinates are copied to clipboard
  5213. if modifiers == QtCore.Qt.ShiftModifier:
  5214. # do not auto open the Project Tab
  5215. self.click_noproject = True
  5216. self.clipboard.setText(
  5217. self.defaults["global_point_clipboard_format"] %
  5218. (self.decimals, self.pos[0], self.decimals, self.pos[1])
  5219. )
  5220. self.inform.emit('[success] %s' % _("Coordinates copied to clipboard."))
  5221. return
  5222. if self.doubleclick is True:
  5223. self.doubleclick = False
  5224. if self.collection.get_selected():
  5225. self.ui.notebook.setCurrentWidget(self.ui.properties_tab)
  5226. if self.ui.splitter.sizes()[0] == 0:
  5227. self.ui.splitter.setSizes([1, 1])
  5228. try:
  5229. # delete the selection shape(S) as it may be in the way
  5230. self.delete_selection_shape()
  5231. self.delete_hover_shape()
  5232. except Exception as e:
  5233. log.warning("FlatCAMApp.on_mouse_click_release_over_plot() double click --> Error: %s" % str(e))
  5234. return
  5235. else:
  5236. # WORKAROUND for LEGACY MODE
  5237. if self.is_legacy is True:
  5238. # if there is no move on canvas then we have no dragging selection
  5239. if self.dx == 0 or self.dy == 0:
  5240. self.selection_type = None
  5241. if self.selection_type is not None:
  5242. try:
  5243. self.selection_area_handler(self.pos, pos, self.selection_type)
  5244. self.selection_type = None
  5245. except Exception as e:
  5246. log.warning("FlatCAMApp.on_mouse_click_release_over_plot() select area --> Error: %s" % str(e))
  5247. return
  5248. else:
  5249. key_modifier = QtWidgets.QApplication.keyboardModifiers()
  5250. if key_modifier == QtCore.Qt.ShiftModifier:
  5251. mod_key = 'Shift'
  5252. elif key_modifier == QtCore.Qt.ControlModifier:
  5253. mod_key = 'Control'
  5254. else:
  5255. mod_key = None
  5256. try:
  5257. if self.command_active is None:
  5258. # If the CTRL key is pressed when the LMB is clicked then if the object is selected it will
  5259. # deselect, and if it's not selected then it will be selected
  5260. # If there is no active command (self.command_active is None) then we check if we clicked
  5261. # on a object by checking the bounding limits against mouse click position
  5262. if mod_key == self.defaults["global_mselect_key"]:
  5263. self.select_objects(key='multisel')
  5264. else:
  5265. # If there is no active command (self.command_active is None) then we check if
  5266. # we clicked on a object by checking the bounding limits against mouse click position
  5267. self.select_objects()
  5268. self.delete_hover_shape()
  5269. except Exception as e:
  5270. log.warning("FlatCAMApp.on_mouse_click_release_over_plot() select click --> Error: %s" % str(e))
  5271. return
  5272. def selection_area_handler(self, start_pos, end_pos, sel_type):
  5273. """
  5274. :param start_pos: mouse position when the selection LMB click was done
  5275. :param end_pos: mouse position when the left mouse button is released
  5276. :param sel_type: if True it's a left to right selection (enclosure), if False it's a 'touch' selection
  5277. :return:
  5278. """
  5279. poly_selection = Polygon([start_pos, (end_pos[0], start_pos[1]), end_pos, (start_pos[0], end_pos[1])])
  5280. # delete previous selection shape
  5281. self.delete_selection_shape()
  5282. # make all objects inactive
  5283. self.collection.set_all_inactive()
  5284. for obj in self.collection.get_list():
  5285. try:
  5286. # select the object(s) only if it is enabled (plotted)
  5287. if obj.options['plot']:
  5288. # it's a line without area
  5289. if obj.options['xmin'] == obj.options['xmax'] or obj.options['ymin'] == obj.options['ymax']:
  5290. poly_obj = unary_union(obj.solid_geometry).buffer(0.001)
  5291. # it's a geometry with area
  5292. else:
  5293. poly_obj = Polygon([(obj.options['xmin'], obj.options['ymin']),
  5294. (obj.options['xmax'], obj.options['ymin']),
  5295. (obj.options['xmax'], obj.options['ymax']),
  5296. (obj.options['xmin'], obj.options['ymax'])])
  5297. if poly_obj.is_empty or not poly_obj.is_valid:
  5298. continue
  5299. if sel_type is True:
  5300. if poly_obj.within(poly_selection):
  5301. # create the selection box around the selected object
  5302. if self.defaults['global_selection_shape'] is True:
  5303. self.draw_selection_shape(obj)
  5304. self.collection.set_active(obj.options['name'])
  5305. else:
  5306. if poly_selection.intersects(poly_obj):
  5307. # create the selection box around the selected object
  5308. if self.defaults['global_selection_shape'] is True:
  5309. self.draw_selection_shape(obj)
  5310. self.collection.set_active(obj.options['name'])
  5311. obj.selection_shape_drawn = True
  5312. except Exception as e:
  5313. # the Exception here will happen if we try to select on screen and we have an newly (and empty)
  5314. # just created Geometry or Excellon object that do not have the xmin, xmax, ymin, ymax options.
  5315. # In this case poly_obj creation (see above) will fail
  5316. log.debug("App.selection_area_handler() --> %s" % str(e))
  5317. def select_objects(self, key=None):
  5318. """
  5319. Will select objects clicked on canvas
  5320. :param key: for future use in cumulative selection
  5321. :return:
  5322. """
  5323. # list where we store the overlapped objects under our mouse left click position
  5324. if key is None:
  5325. self.objects_under_the_click_list = []
  5326. # Populate the list with the overlapped objects on the click position
  5327. curr_x, curr_y = self.pos
  5328. for obj in self.all_objects_list:
  5329. # ScriptObject and DocumentObject objects can't be selected
  5330. if obj.kind == 'script' or obj.kind == 'document':
  5331. continue
  5332. if key == 'multisel' and obj.options['name'] in self.objects_under_the_click_list:
  5333. continue
  5334. if (curr_x >= obj.options['xmin']) and (curr_x <= obj.options['xmax']) and \
  5335. (curr_y >= obj.options['ymin']) and (curr_y <= obj.options['ymax']):
  5336. if obj.options['name'] not in self.objects_under_the_click_list:
  5337. if obj.options['plot']:
  5338. # add objects to the objects_under_the_click list only if the object is plotted
  5339. # (active and not disabled)
  5340. self.objects_under_the_click_list.append(obj.options['name'])
  5341. try:
  5342. if self.objects_under_the_click_list:
  5343. curr_sel_obj = self.collection.get_active()
  5344. # case when there is only an object under the click and we toggle it
  5345. if len(self.objects_under_the_click_list) == 1:
  5346. if curr_sel_obj is None:
  5347. self.collection.set_active(self.objects_under_the_click_list[0])
  5348. curr_sel_obj = self.collection.get_active()
  5349. # create the selection box around the selected object
  5350. if self.defaults['global_selection_shape'] is True:
  5351. self.draw_selection_shape(curr_sel_obj)
  5352. curr_sel_obj.selection_shape_drawn = True
  5353. elif curr_sel_obj.options['name'] not in self.objects_under_the_click_list:
  5354. self.collection.on_objects_selection(False)
  5355. self.delete_selection_shape()
  5356. curr_sel_obj.selection_shape_drawn = False
  5357. self.collection.set_active(self.objects_under_the_click_list[0])
  5358. curr_sel_obj = self.collection.get_active()
  5359. # create the selection box around the selected object
  5360. if self.defaults['global_selection_shape'] is True:
  5361. self.draw_selection_shape(curr_sel_obj)
  5362. curr_sel_obj.selection_shape_drawn = True
  5363. self.selected_message(curr_sel_obj=curr_sel_obj)
  5364. elif curr_sel_obj.selection_shape_drawn is False:
  5365. if self.defaults['global_selection_shape'] is True:
  5366. self.draw_selection_shape(curr_sel_obj)
  5367. curr_sel_obj.selection_shape_drawn = True
  5368. else:
  5369. self.collection.on_objects_selection(False)
  5370. self.delete_selection_shape()
  5371. if self.call_source != 'app':
  5372. self.call_source = 'app'
  5373. self.selected_message(curr_sel_obj=curr_sel_obj)
  5374. else:
  5375. # If there is no selected object
  5376. # make active the first element of the overlapped objects list
  5377. if self.collection.get_active() is None:
  5378. self.collection.set_active(self.objects_under_the_click_list[0])
  5379. self.collection.get_by_name(self.objects_under_the_click_list[0]).selection_shape_drawn = True
  5380. name_sel_obj = self.collection.get_active().options['name']
  5381. # In case that there is a selected object but it is not in the overlapped object list
  5382. # make that object inactive and activate the first element in the overlapped object list
  5383. if name_sel_obj not in self.objects_under_the_click_list:
  5384. self.collection.set_inactive(name_sel_obj)
  5385. name_sel_obj = self.objects_under_the_click_list[0]
  5386. self.collection.set_active(name_sel_obj)
  5387. else:
  5388. sel_idx = self.objects_under_the_click_list.index(name_sel_obj)
  5389. self.collection.set_all_inactive()
  5390. self.collection.set_active(
  5391. self.objects_under_the_click_list[(sel_idx + 1) % len(self.objects_under_the_click_list)])
  5392. curr_sel_obj = self.collection.get_active()
  5393. # delete the possible selection box around a possible selected object
  5394. self.delete_selection_shape()
  5395. curr_sel_obj.selection_shape_drawn = False
  5396. # create the selection box around the selected object
  5397. if self.defaults['global_selection_shape'] is True:
  5398. self.draw_selection_shape(curr_sel_obj)
  5399. curr_sel_obj.selection_shape_drawn = True
  5400. self.selected_message(curr_sel_obj=curr_sel_obj)
  5401. else:
  5402. # deselect everything
  5403. self.collection.on_objects_selection(False)
  5404. # delete the possible selection box around a possible selected object
  5405. self.delete_selection_shape()
  5406. for o in self.collection.get_list():
  5407. o.selection_shape_drawn = False
  5408. # and as a convenience move the focus to the Project tab because Selected tab is now empty but
  5409. # only when working on App
  5410. if self.call_source == 'app':
  5411. if self.click_noproject is False:
  5412. # if the Tool Tab is in focus don't change focus to Project Tab
  5413. if not self.ui.notebook.currentWidget() is self.ui.tool_tab:
  5414. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  5415. else:
  5416. # restore auto open the Project Tab
  5417. self.click_noproject = False
  5418. # delete any text in the status bar, implicitly the last object name that was selected
  5419. # self.inform.emit("")
  5420. else:
  5421. self.call_source = 'app'
  5422. except Exception as e:
  5423. log.error("[ERROR] Something went bad in App.select_objects(). %s" % str(e))
  5424. def selected_message(self, curr_sel_obj):
  5425. if curr_sel_obj:
  5426. if curr_sel_obj.kind == 'gerber':
  5427. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  5428. color='green',
  5429. name=str(curr_sel_obj.options['name']),
  5430. tx=_("selected"))
  5431. )
  5432. elif curr_sel_obj.kind == 'excellon':
  5433. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  5434. color='brown',
  5435. name=str(curr_sel_obj.options['name']),
  5436. tx=_("selected"))
  5437. )
  5438. elif curr_sel_obj.kind == 'cncjob':
  5439. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  5440. color='blue',
  5441. name=str(curr_sel_obj.options['name']),
  5442. tx=_("selected"))
  5443. )
  5444. elif curr_sel_obj.kind == 'geometry':
  5445. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  5446. color='red',
  5447. name=str(curr_sel_obj.options['name']),
  5448. tx=_("selected"))
  5449. )
  5450. def delete_hover_shape(self):
  5451. self.hover_shapes.clear()
  5452. self.hover_shapes.redraw()
  5453. def draw_hover_shape(self, sel_obj, color=None):
  5454. """
  5455. :param sel_obj: The object for which the hover shape must be drawn
  5456. :param color: The color of the hover shape
  5457. :return: None
  5458. """
  5459. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  5460. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  5461. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  5462. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  5463. hover_rect = Polygon([pt1, pt2, pt3, pt4])
  5464. if self.defaults['units'].upper() == 'MM':
  5465. hover_rect = hover_rect.buffer(-0.1)
  5466. hover_rect = hover_rect.buffer(0.2)
  5467. else:
  5468. hover_rect = hover_rect.buffer(-0.00393)
  5469. hover_rect = hover_rect.buffer(0.00787)
  5470. # if color:
  5471. # face = Color(color)
  5472. # face.alpha = 0.2
  5473. # outline = Color(color, alpha=0.8)
  5474. # else:
  5475. # face = Color(self.defaults['global_sel_fill'])
  5476. # face.alpha = 0.2
  5477. # outline = self.defaults['global_sel_line']
  5478. if color:
  5479. face = color[:-2] + str(hex(int(0.2 * 255)))[2:]
  5480. outline = color[:-2] + str(hex(int(0.8 * 255)))[2:]
  5481. else:
  5482. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.2 * 255)))[2:]
  5483. outline = self.defaults['global_sel_line']
  5484. self.hover_shapes.add(hover_rect, color=outline, face_color=face, update=True, layer=0, tolerance=None)
  5485. if self.is_legacy is True:
  5486. self.hover_shapes.redraw()
  5487. def delete_selection_shape(self):
  5488. self.move_tool.sel_shapes.clear()
  5489. self.move_tool.sel_shapes.redraw()
  5490. def draw_selection_shape(self, sel_obj, color=None):
  5491. """
  5492. Will draw a selection shape around the selected object.
  5493. :param sel_obj: The object for which the selection shape must be drawn
  5494. :param color: The color for the selection shape.
  5495. :return: None
  5496. """
  5497. if sel_obj is None:
  5498. return
  5499. # it's a line without area
  5500. if sel_obj.options['xmin'] == sel_obj.options['xmax'] or sel_obj.options['ymin'] == sel_obj.options['ymax']:
  5501. sel_rect = unary_union(sel_obj.solid_geometry).buffer(0.100001)
  5502. # it's a geometry with area
  5503. else:
  5504. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  5505. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  5506. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  5507. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  5508. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  5509. b_sel_rect = None
  5510. try:
  5511. if self.defaults['units'].upper() == 'MM':
  5512. b_sel_rect = sel_rect.buffer(-0.1)
  5513. b_sel_rect = b_sel_rect.buffer(0.2)
  5514. else:
  5515. b_sel_rect = sel_rect.buffer(-0.00393)
  5516. b_sel_rect = b_sel_rect.buffer(0.00787)
  5517. except Exception:
  5518. pass
  5519. if b_sel_rect.is_empty or not b_sel_rect.is_valid or b_sel_rect is None:
  5520. b_sel_rect = sel_rect
  5521. if color:
  5522. face = color[:-2] + str(hex(int(0.2 * 255)))[2:]
  5523. outline = color[:-2] + str(hex(int(0.8 * 255)))[2:]
  5524. else:
  5525. if self.is_legacy is False:
  5526. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.2 * 255)))[2:]
  5527. outline = self.defaults['global_sel_line'][:-2] + str(hex(int(0.8 * 255)))[2:]
  5528. else:
  5529. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.4 * 255)))[2:]
  5530. outline = self.defaults['global_sel_line'][:-2] + str(hex(int(1.0 * 255)))[2:]
  5531. self.sel_objects_list.append(self.move_tool.sel_shapes.add(b_sel_rect,
  5532. color=outline,
  5533. face_color=face,
  5534. update=True,
  5535. layer=0,
  5536. tolerance=None))
  5537. if self.is_legacy is True:
  5538. self.move_tool.sel_shapes.redraw()
  5539. def draw_moving_selection_shape(self, old_coords, coords, **kwargs):
  5540. """
  5541. Will draw a selection shape when dragging mouse on canvas.
  5542. :param old_coords: Old coordinates
  5543. :param coords: New coordinates
  5544. :param kwargs: Keyword arguments
  5545. :return:
  5546. """
  5547. if 'color' in kwargs:
  5548. color = kwargs['color']
  5549. else:
  5550. color = self.defaults['global_sel_line']
  5551. if 'face_color' in kwargs:
  5552. face_color = kwargs['face_color']
  5553. else:
  5554. face_color = self.defaults['global_sel_fill']
  5555. if 'face_alpha' in kwargs:
  5556. face_alpha = kwargs['face_alpha']
  5557. else:
  5558. face_alpha = 0.3
  5559. x0, y0 = old_coords
  5560. x1, y1 = coords
  5561. pt1 = (x0, y0)
  5562. pt2 = (x1, y0)
  5563. pt3 = (x1, y1)
  5564. pt4 = (x0, y1)
  5565. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  5566. # color_t = Color(face_color)
  5567. # color_t.alpha = face_alpha
  5568. color_t = face_color[:-2] + str(hex(int(face_alpha * 255)))[2:]
  5569. self.move_tool.sel_shapes.add(sel_rect, color=color, face_color=color_t, update=True,
  5570. layer=0, tolerance=None)
  5571. if self.is_legacy is True:
  5572. self.move_tool.sel_shapes.redraw()
  5573. def obj_properties(self):
  5574. """
  5575. Will launch the object Properties Tool
  5576. :return:
  5577. """
  5578. self.defaults.report_usage("obj_properties()")
  5579. self.properties_tool.run(toggle=False)
  5580. def on_project_context_save(self):
  5581. """
  5582. Wrapper, will save the object function of it's type
  5583. :return:
  5584. """
  5585. sel_objects = self.collection.get_selected()
  5586. len_objects = len(sel_objects)
  5587. cnt = 0
  5588. if len_objects > 1:
  5589. for o in sel_objects:
  5590. if o.kind == 'cncjob':
  5591. cnt += 1
  5592. if len_objects == cnt:
  5593. # all selected objects are of type CNCJOB therefore we issue a multiple save
  5594. _filter_ = self.defaults['cncjob_save_filters'] + \
  5595. ";;RML1 Files .rol (*.rol);;HPGL Files .plt (*.plt)"
  5596. dir_file_to_save = self.get_last_save_folder() + '/multi_save'
  5597. try:
  5598. filename, _f = FCFileSaveDialog.get_saved_filename(
  5599. caption=_("Export Code ..."),
  5600. directory=dir_file_to_save,
  5601. ext_filter=_filter_
  5602. )
  5603. except TypeError:
  5604. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export Code ..."),
  5605. ext_filter=_filter_)
  5606. filename = filename.rpartition('/')[0]
  5607. for ob in sel_objects:
  5608. ob.read_form()
  5609. fname = '%s/%s' % (filename, ob.options['name'])
  5610. ob.export_gcode_handler(fname, is_gcode=True)
  5611. return
  5612. obj = self.collection.get_active()
  5613. if type(obj) == GeometryObject:
  5614. self.on_file_exportdxf()
  5615. elif type(obj) == ExcellonObject:
  5616. self.on_file_saveexcellon()
  5617. elif type(obj) == CNCJobObject:
  5618. obj.on_exportgcode_button_click()
  5619. elif type(obj) == GerberObject:
  5620. self.on_file_savegerber()
  5621. elif type(obj) == ScriptObject:
  5622. self.on_file_savescript()
  5623. elif type(obj) == DocumentObject:
  5624. self.on_file_savedocument()
  5625. def obj_move(self):
  5626. """
  5627. Callback for the Move menu entry in various Context Menu's.
  5628. :return:
  5629. """
  5630. self.defaults.report_usage("obj_move()")
  5631. self.move_tool.run(toggle=False)
  5632. # ###############################################################################################################
  5633. # ### The following section has the functions that are displayed and call the Editor tab CNCJob Tab #############
  5634. # ###############################################################################################################
  5635. def init_code_editor(self, name):
  5636. self.text_editor_tab = AppTextEditor(app=self, plain_text=True)
  5637. # add the tab if it was closed
  5638. self.ui.plot_tab_area.addTab(self.text_editor_tab, '%s' % name)
  5639. self.text_editor_tab.setObjectName('text_editor_tab')
  5640. # delete the absolute and relative position and messages in the infobar
  5641. # self.ui.position_label.setText("")
  5642. # self.ui.rel_position_label.setText("")
  5643. # hide coordinates toolbars in the infobar while in DB
  5644. self.ui.coords_toolbar.hide()
  5645. self.ui.delta_coords_toolbar.hide()
  5646. self.toggle_codeeditor = True
  5647. self.text_editor_tab.code_editor.completer_enable = False
  5648. self.text_editor_tab.buttonRun.hide()
  5649. # make sure to keep a reference to the code editor
  5650. self.reference_code_editor = self.text_editor_tab.code_editor
  5651. # Switch plot_area to CNCJob tab
  5652. self.ui.plot_tab_area.setCurrentWidget(self.text_editor_tab)
  5653. def on_view_source(self):
  5654. """
  5655. Called when the user wants to see the source file of the selected object
  5656. :return:
  5657. """
  5658. try:
  5659. obj = self.collection.get_active()
  5660. except Exception as e:
  5661. log.debug("App.on_view_source() --> %s" % str(e))
  5662. self.inform.emit('[WARNING_NOTCL] %s' % _("Select an Gerber or Excellon file to view it's source file."))
  5663. return 'fail'
  5664. if obj is None:
  5665. self.inform.emit('[WARNING_NOTCL] %s' % _("Select an Gerber or Excellon file to view it's source file."))
  5666. return 'fail'
  5667. self.inform.emit('%s' % _("Viewing the source code of the selected object."))
  5668. self.proc_container.view.set_busy(_("Loading..."))
  5669. flt = "All Files (*.*)"
  5670. if obj.kind == 'gerber':
  5671. flt = "Gerber Files .gbr (*.GBR);;PDF Files .pdf (*.PDF);;All Files (*.*)"
  5672. elif obj.kind == 'excellon':
  5673. flt = "Excellon Files .drl (*.DRL);;PDF Files .pdf (*.PDF);;All Files (*.*)"
  5674. elif obj.kind == 'cncjob':
  5675. flt = "GCode Files .nc (*.NC);;PDF Files .pdf (*.PDF);;All Files (*.*)"
  5676. self.source_editor_tab = AppTextEditor(app=self, plain_text=True)
  5677. # add the tab if it was closed
  5678. self.ui.plot_tab_area.addTab(self.source_editor_tab, '%s' % _("Source Editor"))
  5679. self.source_editor_tab.setObjectName('source_editor_tab')
  5680. # delete the absolute and relative position and messages in the infobar
  5681. # self.ui.position_label.setText("")
  5682. # self.ui.rel_position_label.setText("")
  5683. # hide coordinates toolbars in the infobar while in DB
  5684. self.ui.coords_toolbar.hide()
  5685. self.ui.delta_coords_toolbar.hide()
  5686. self.source_editor_tab.code_editor.completer_enable = False
  5687. self.source_editor_tab.buttonRun.hide()
  5688. # Switch plot_area to CNCJob tab
  5689. self.ui.plot_tab_area.setCurrentWidget(self.source_editor_tab)
  5690. try:
  5691. self.source_editor_tab.buttonOpen.clicked.disconnect()
  5692. except TypeError:
  5693. pass
  5694. self.source_editor_tab.buttonOpen.clicked.connect(lambda: self.source_editor_tab.handleOpen(filt=flt))
  5695. try:
  5696. self.source_editor_tab.buttonSave.clicked.disconnect()
  5697. except TypeError:
  5698. pass
  5699. self.source_editor_tab.buttonSave.clicked.connect(lambda: self.source_editor_tab.handleSaveGCode(filt=flt))
  5700. # then append the text from GCode to the text editor
  5701. if obj.kind == 'cncjob':
  5702. try:
  5703. file = obj.export_gcode(to_file=True)
  5704. if file == 'fail':
  5705. return 'fail'
  5706. except AttributeError:
  5707. self.inform.emit('[WARNING_NOTCL] %s' %
  5708. _("There is no selected object for which to see it's source file code."))
  5709. return 'fail'
  5710. else:
  5711. try:
  5712. file = StringIO(obj.source_file)
  5713. except (AttributeError, TypeError):
  5714. self.inform.emit('[WARNING_NOTCL] %s' %
  5715. _("There is no selected object for which to see it's source file code."))
  5716. return 'fail'
  5717. self.source_editor_tab.t_frame.hide()
  5718. try:
  5719. self.source_editor_tab.load_text(file.getvalue(), clear_text=True, move_to_start=True)
  5720. except Exception as e:
  5721. log.debug('App.on_view_source() -->%s' % str(e))
  5722. self.inform.emit('[ERROR] %s: %s' % (_('Failed to load the source code for the selected object'), str(e)))
  5723. return
  5724. self.source_editor_tab.t_frame.show()
  5725. self.proc_container.view.set_idle()
  5726. # self.ui.show()
  5727. def on_toggle_code_editor(self):
  5728. self.defaults.report_usage("on_toggle_code_editor()")
  5729. if self.toggle_codeeditor is False:
  5730. self.init_code_editor(name=_("Code Editor"))
  5731. self.text_editor_tab.buttonOpen.clicked.disconnect()
  5732. self.text_editor_tab.buttonOpen.clicked.connect(self.text_editor_tab.handleOpen)
  5733. self.text_editor_tab.buttonSave.clicked.disconnect()
  5734. self.text_editor_tab.buttonSave.clicked.connect(self.text_editor_tab.handleSaveGCode)
  5735. else:
  5736. for idx in range(self.ui.plot_tab_area.count()):
  5737. if self.ui.plot_tab_area.widget(idx).objectName() == "text_editor_tab":
  5738. self.ui.plot_tab_area.closeTab(idx)
  5739. break
  5740. self.toggle_codeeditor = False
  5741. def on_code_editor_close(self):
  5742. self.toggle_codeeditor = False
  5743. def goto_text_line(self):
  5744. """
  5745. Will scroll a text to the specified text line.
  5746. :return: None
  5747. """
  5748. dia_box = Dialog_box(title=_("Go to Line ..."),
  5749. label=_("Line:"),
  5750. icon=QtGui.QIcon(self.resource_location + '/jump_to16.png'),
  5751. initial_text='')
  5752. try:
  5753. line = int(dia_box.location) - 1
  5754. except (ValueError, TypeError):
  5755. line = 0
  5756. if dia_box.ok:
  5757. # make sure to move first the cursor at the end so after finding the line the line will be positioned
  5758. # at the top of the window
  5759. self.ui.plot_tab_area.currentWidget().code_editor.moveCursor(QTextCursor.End)
  5760. # get the document() of the AppTextEditor
  5761. doc = self.ui.plot_tab_area.currentWidget().code_editor.document()
  5762. # create a Text Cursor based on the searched line
  5763. cursor = QTextCursor(doc.findBlockByLineNumber(line))
  5764. # set cursor of the code editor with the cursor at the searcehd line
  5765. self.ui.plot_tab_area.currentWidget().code_editor.setTextCursor(cursor)
  5766. def plot_all(self, fit_view=True, muted=False, use_thread=True):
  5767. """
  5768. Re-generates all plots from all objects.
  5769. :param fit_view: if True will plot the objects and will adjust the zoom to fit all plotted objects into view
  5770. :param muted: if True don't print messages
  5771. :param use_thread: if True will use threading for plotting the objects
  5772. :return: None
  5773. """
  5774. self.log.debug("Plot_all()")
  5775. if muted is not True:
  5776. self.inform[str, bool].emit('%s...' % _("Redrawing all objects"), False)
  5777. for plot_obj in self.collection.get_list():
  5778. def worker_task(obj):
  5779. with self.proc_container.new("Plotting"):
  5780. obj.plot(kind=self.defaults["cncjob_plot_kind"])
  5781. if fit_view is True:
  5782. self.app_obj.object_plotted.emit(obj)
  5783. if use_thread is True:
  5784. # Send to worker
  5785. self.worker_task.emit({'fcn': worker_task, 'params': [plot_obj]})
  5786. else:
  5787. worker_task(plot_obj)
  5788. def register_folder(self, filename):
  5789. """
  5790. Register the last folder used by the app to open something
  5791. :param filename: the last folder is extracted from the filename
  5792. :return: None
  5793. """
  5794. self.defaults["global_last_folder"] = os.path.split(str(filename))[0]
  5795. def register_save_folder(self, filename):
  5796. """
  5797. Register the last folder used by the app to save something
  5798. :param filename: the last folder is extracted from the filename
  5799. :return: None
  5800. """
  5801. self.defaults["global_last_save_folder"] = os.path.split(str(filename))[0]
  5802. # def set_progress_bar(self, percentage, text=""):
  5803. # """
  5804. # Set a progress bar to a value (percentage)
  5805. #
  5806. # :param percentage: Value set to the progressbar
  5807. # :param text: Not used
  5808. # :return: None
  5809. # """
  5810. # self.ui.progress_bar.setValue(int(percentage))
  5811. def setup_recent_items(self):
  5812. """
  5813. Setup a dictionary with the recent files accessed, organized by type
  5814. :return:
  5815. """
  5816. icons = {
  5817. "gerber": self.resource_location + "/flatcam_icon16.png",
  5818. "excellon": self.resource_location + "/drill16.png",
  5819. 'geometry': self.resource_location + "/geometry16.png",
  5820. "cncjob": self.resource_location + "/cnc16.png",
  5821. "script": self.resource_location + "/script_new24.png",
  5822. "document": self.resource_location + "/notes16_1.png",
  5823. "project": self.resource_location + "/project16.png",
  5824. "svg": self.resource_location + "/geometry16.png",
  5825. "dxf": self.resource_location + "/dxf16.png",
  5826. "pdf": self.resource_location + "/pdf32.png",
  5827. "image": self.resource_location + "/image16.png"
  5828. }
  5829. try:
  5830. image_opener = self.image_tool.import_image
  5831. except AttributeError:
  5832. image_opener = None
  5833. openers = {
  5834. 'gerber': lambda fname: self.worker_task.emit({'fcn': self.f_handlers.open_gerber, 'params': [fname]}),
  5835. 'excellon': lambda fname: self.worker_task.emit({'fcn': self.f_handlers.open_excellon, 'params': [fname]}),
  5836. 'geometry': lambda fname: self.worker_task.emit({'fcn': self.f_handlers.import_dxf, 'params': [fname]}),
  5837. 'cncjob': lambda fname: self.worker_task.emit({'fcn': self.f_handlers.open_gcode, 'params': [fname]}),
  5838. "script": lambda fname: self.worker_task.emit({'fcn': self.f_handlers.open_script, 'params': [fname]}),
  5839. "document": None,
  5840. 'project': self.f_handlers.open_project,
  5841. 'svg': self.f_handlers.import_svg,
  5842. 'dxf': self.f_handlers.import_dxf,
  5843. 'image': image_opener,
  5844. 'pdf': lambda fname: self.worker_task.emit({'fcn': self.pdf_tool.open_pdf, 'params': [fname]})
  5845. }
  5846. # Open recent file for files
  5847. try:
  5848. f = open(self.data_path + '/recent.json')
  5849. except IOError:
  5850. App.log.error("Failed to load recent item list.")
  5851. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to load recent item list."))
  5852. return
  5853. try:
  5854. self.recent = json.load(f)
  5855. except json.errors.JSONDecodeError:
  5856. App.log.error("Failed to parse recent item list.")
  5857. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to parse recent item list."))
  5858. f.close()
  5859. return
  5860. f.close()
  5861. # Open recent file for projects
  5862. try:
  5863. fp = open(self.data_path + '/recent_projects.json')
  5864. except IOError:
  5865. App.log.error("Failed to load recent project item list.")
  5866. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to load recent projects item list."))
  5867. return
  5868. try:
  5869. self.recent_projects = json.load(fp)
  5870. except json.errors.JSONDecodeError:
  5871. App.log.error("Failed to parse recent project item list.")
  5872. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to parse recent project item list."))
  5873. fp.close()
  5874. return
  5875. fp.close()
  5876. # Closure needed to create callbacks in a loop.
  5877. # Otherwise late binding occurs.
  5878. def make_callback(func, fname):
  5879. def opener():
  5880. func(fname)
  5881. return opener
  5882. def reset_recent_files():
  5883. # Reset menu
  5884. self.ui.recent.clear()
  5885. self.recent = []
  5886. try:
  5887. ff = open(self.data_path + '/recent.json', 'w')
  5888. except IOError:
  5889. App.log.error("Failed to open recent items file for writing.")
  5890. return
  5891. json.dump(self.recent, ff)
  5892. def reset_recent_projects():
  5893. # Reset menu
  5894. self.ui.recent_projects.clear()
  5895. self.recent_projects = []
  5896. try:
  5897. frp = open(self.data_path + '/recent_projects.json', 'w')
  5898. except IOError:
  5899. App.log.error("Failed to open recent projects items file for writing.")
  5900. return
  5901. json.dump(self.recent, frp)
  5902. # Reset menu
  5903. self.ui.recent.clear()
  5904. self.ui.recent_projects.clear()
  5905. # Create menu items for projects
  5906. for recent in self.recent_projects:
  5907. filename = recent['filename'].split('/')[-1].split('\\')[-1]
  5908. if recent['kind'] == 'project':
  5909. try:
  5910. action = QtWidgets.QAction(QtGui.QIcon(icons[recent["kind"]]), filename, self)
  5911. # Attach callback
  5912. o = make_callback(openers[recent["kind"]], recent['filename'])
  5913. action.triggered.connect(o)
  5914. self.ui.recent_projects.addAction(action)
  5915. except KeyError:
  5916. App.log.error("Unsupported file type: %s" % recent["kind"])
  5917. # Last action in Recent Files menu is one that Clear the content
  5918. clear_action_proj = QtWidgets.QAction(QtGui.QIcon(self.resource_location + '/trash32.png'),
  5919. (_("Clear Recent projects")), self)
  5920. clear_action_proj.triggered.connect(reset_recent_projects)
  5921. self.ui.recent_projects.addSeparator()
  5922. self.ui.recent_projects.addAction(clear_action_proj)
  5923. # Create menu items for files
  5924. for recent in self.recent:
  5925. filename = recent['filename'].split('/')[-1].split('\\')[-1]
  5926. if recent['kind'] != 'project':
  5927. try:
  5928. action = QtWidgets.QAction(QtGui.QIcon(icons[recent["kind"]]), filename, self)
  5929. # Attach callback
  5930. o = make_callback(openers[recent["kind"]], recent['filename'])
  5931. action.triggered.connect(o)
  5932. self.ui.recent.addAction(action)
  5933. except KeyError:
  5934. App.log.error("Unsupported file type: %s" % recent["kind"])
  5935. # Last action in Recent Files menu is one that Clear the content
  5936. clear_action = QtWidgets.QAction(QtGui.QIcon(self.resource_location + '/trash32.png'),
  5937. (_("Clear Recent files")), self)
  5938. clear_action.triggered.connect(reset_recent_files)
  5939. self.ui.recent.addSeparator()
  5940. self.ui.recent.addAction(clear_action)
  5941. # self.builder.get_object('open_recent').set_submenu(recent_menu)
  5942. # self.ui.menufilerecent.set_submenu(recent_menu)
  5943. # recent_menu.show_all()
  5944. # self.ui.recent.show()
  5945. self.log.debug("Recent items list has been populated.")
  5946. def on_properties_tab_click(self, index):
  5947. if self.ui.properties_scroll_area.widget().objectName() == 'default_properties':
  5948. self.setup_default_properties_tab()
  5949. def setup_default_properties_tab(self):
  5950. """
  5951. Default text for the Properties tab when is not taken by the Object UI.
  5952. :return:
  5953. """
  5954. # label = QtWidgets.QLabel("Choose an item from Project")
  5955. # label.setAlignment(QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter)
  5956. # sel_title = QtWidgets.QTextEdit()
  5957. # sel_title.setTextInteractionFlags(QtCore.Qt.NoTextInteraction)
  5958. # sel_title.setFrameStyle(QtWidgets.QFrame.NoFrame)
  5959. #
  5960. # f_settings = QSettings("Open Source", "FlatCAM")
  5961. # if f_settings.contains("notebook_font_size"):
  5962. # fsize = f_settings.value('notebook_font_size', type=int)
  5963. # else:
  5964. # fsize = 12
  5965. #
  5966. # tsize = fsize + int(fsize / 2)
  5967. #
  5968. # selected_text = ''
  5969. #
  5970. # sel_title.setText(selected_text)
  5971. # sel_title.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
  5972. # Tree Widget
  5973. d_properties_tw = FCTree(columns=2)
  5974. d_properties_tw.setObjectName("default_properties")
  5975. d_properties_tw.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
  5976. d_properties_tw.setStyleSheet("QTreeWidget {border: 0px;}")
  5977. root = d_properties_tw.invisibleRootItem()
  5978. font = QtGui.QFont()
  5979. font.setBold(True)
  5980. p_color = QtGui.QColor("#000000") if self.defaults['global_gray_icons'] is False else QtGui.QColor("#FFFFFF")
  5981. # main Items categories
  5982. general_cat = d_properties_tw.addParent(root, _('General'), expanded=True, color=p_color, font=font)
  5983. d_properties_tw.addChild(parent=general_cat,
  5984. title=['%s:' % _("Name"), '%s' % _("FlatCAM Evo")], column1=True)
  5985. d_properties_tw.addChild(parent=general_cat,
  5986. title=['%s:' % _("Version"), '%s' % str(self.version)], column1=True)
  5987. d_properties_tw.addChild(parent=general_cat,
  5988. title=['%s:' % _("Release date"), '%s' % str(self.version_date)], column1=True)
  5989. grid_cat = d_properties_tw.addParent(root, _('Grid'), expanded=True, color=p_color, font=font)
  5990. d_properties_tw.addChild(parent=grid_cat,
  5991. title=['%s:' % _("Displayed"), '%s' % str(self.defaults['global_grid_lines'])],
  5992. column1=True)
  5993. d_properties_tw.addChild(parent=grid_cat,
  5994. title=['%s:' % _("Snap"), '%s' % str(self.defaults['global_grid_snap'])],
  5995. column1=True)
  5996. d_properties_tw.addChild(parent=grid_cat,
  5997. title=['%s:' % _("X value"), '%s' % str(self.ui.grid_gap_x_entry.get_value())],
  5998. column1=True)
  5999. d_properties_tw.addChild(parent=grid_cat,
  6000. title=['%s:' % _("Y value"), '%s' % str(self.ui.grid_gap_y_entry.get_value())],
  6001. column1=True)
  6002. canvas_cat = d_properties_tw.addParent(root, _('Canvas'), expanded=True, color=p_color, font=font)
  6003. d_properties_tw.addChild(parent=canvas_cat,
  6004. title=['%s:' % _("Axis"), '%s' % str(self.defaults['global_axis'])],
  6005. column1=True)
  6006. d_properties_tw.addChild(parent=canvas_cat,
  6007. title=['%s:' % _("Workspace active"),
  6008. '%s' % str(self.defaults['global_workspace'])],
  6009. column1=True)
  6010. d_properties_tw.addChild(parent=canvas_cat,
  6011. title=['%s:' % _("Workspace size"),
  6012. '%s' % str(self.defaults['global_workspaceT'])],
  6013. column1=True)
  6014. d_properties_tw.addChild(parent=canvas_cat,
  6015. title=['%s:' % _("Workspace orientation"),
  6016. '%s' % _("Portrait") if self.defaults[
  6017. 'global_workspace_orientation'] == 'p' else
  6018. _("Landscape")],
  6019. column1=True)
  6020. d_properties_tw.addChild(parent=canvas_cat,
  6021. title=['%s:' % _("HUD"), '%s' % str(self.defaults['global_hud'])],
  6022. column1=True)
  6023. self.ui.properties_scroll_area.setWidget(d_properties_tw)
  6024. def setup_obj_classes(self):
  6025. """
  6026. Sets up application specifics on the FlatCAMObj class. This way the object.app attribute will point to the App
  6027. class.
  6028. :return: None
  6029. """
  6030. FlatCAMObj.app = self
  6031. ObjectCollection.app = self
  6032. Gerber.app = self
  6033. Excellon.app = self
  6034. Geometry.app = self
  6035. CNCjob.app = self
  6036. FCProcess.app = self
  6037. FCProcessContainer.app = self
  6038. OptionsGroupUI.app = self
  6039. def version_check(self):
  6040. """
  6041. Checks for the latest version of the program. Alerts the
  6042. user if theirs is outdated. This method is meant to be run
  6043. in a separate thread.
  6044. :return: None
  6045. """
  6046. self.log.debug("version_check()")
  6047. if self.ui.general_defaults_form.general_app_group.send_stats_cb.get_value() is True:
  6048. full_url = "%s?s=%s&v=%s&os=%s&%s" % (
  6049. App.version_url,
  6050. str(self.defaults['global_serial']),
  6051. str(self.version),
  6052. str(self.os),
  6053. urllib.parse.urlencode(self.defaults["global_stats"])
  6054. )
  6055. # full_url = App.version_url + "?s=" + str(self.defaults['global_serial']) + \
  6056. # "&v=" + str(self.version) + "&os=" + str(self.os) + "&" + \
  6057. # urllib.parse.urlencode(self.defaults["global_stats"])
  6058. else:
  6059. # no_stats dict; just so it won't break things on website
  6060. no_ststs_dict = {}
  6061. no_ststs_dict["global_ststs"] = {}
  6062. full_url = App.version_url + "?s=" + str(self.defaults['global_serial']) + "&v=" + str(self.version)
  6063. full_url += "&os=" + str(self.os) + "&" + urllib.parse.urlencode(no_ststs_dict["global_ststs"])
  6064. App.log.debug("Checking for updates @ %s" % full_url)
  6065. # ## Get the data
  6066. try:
  6067. f = urllib.request.urlopen(full_url)
  6068. except Exception:
  6069. # App.log.warning("Failed checking for latest version. Could not connect.")
  6070. self.log.warning("Failed checking for latest version. Could not connect.")
  6071. self.inform.emit('[WARNING_NOTCL] %s' % _("Failed checking for latest version. Could not connect."))
  6072. return
  6073. try:
  6074. data = json.load(f)
  6075. except Exception as e:
  6076. App.log.error("Could not parse information about latest version.")
  6077. self.inform.emit('[ERROR_NOTCL] %s' % _("Could not parse information about latest version."))
  6078. App.log.debug("json.load(): %s" % str(e))
  6079. f.close()
  6080. return
  6081. f.close()
  6082. # ## Latest version?
  6083. if self.version >= data["version"]:
  6084. App.log.debug("FlatCAM is up to date!")
  6085. self.inform.emit('[success] %s' % _("FlatCAM is up to date!"))
  6086. return
  6087. App.log.debug("Newer version available.")
  6088. self.message.emit(
  6089. _("Newer Version Available"),
  6090. '%s<br><br>><b>%s</b><br>%s' % (
  6091. _("There is a newer version of FlatCAM available for download:"),
  6092. str(data["name"]),
  6093. str(data["message"])
  6094. ),
  6095. _("info")
  6096. )
  6097. def on_plotcanvas_setup(self, container=None):
  6098. """
  6099. This is doing the setup for the plot area (canvas).
  6100. :param container: QT Widget where to install the canvas
  6101. :return: None
  6102. """
  6103. if container:
  6104. plot_container = container
  6105. else:
  6106. plot_container = self.ui.right_layout
  6107. modifier = QtWidgets.QApplication.queryKeyboardModifiers()
  6108. if self.is_legacy is True or modifier == QtCore.Qt.ControlModifier:
  6109. self.is_legacy = True
  6110. self.defaults["global_graphic_engine"] = "2D"
  6111. self.plotcanvas = PlotCanvasLegacy(plot_container, self)
  6112. else:
  6113. try:
  6114. self.plotcanvas = PlotCanvas(plot_container, self)
  6115. except Exception as er:
  6116. msg_txt = traceback.format_exc()
  6117. log.debug("App.on_plotcanvas_setup() failed -> %s" % str(er))
  6118. log.debug("OpenGL canvas initialization failed with the following error.\n" + msg_txt)
  6119. msg = '[ERROR_NOTCL] %s' % _("An internal error has occurred. See shell.\n")
  6120. msg += _("OpenGL canvas initialization failed. HW or HW configuration not supported."
  6121. "Change the graphic engine to Legacy(2D) in Edit -> Preferences -> General tab.\n\n")
  6122. msg += msg_txt
  6123. self.inform.emit(msg)
  6124. return 'fail'
  6125. # So it can receive key presses
  6126. self.plotcanvas.native.setFocus()
  6127. if self.is_legacy is False:
  6128. pan_button = 2 if self.defaults["global_pan_button"] == '2' else 3
  6129. # Set the mouse button for panning
  6130. self.plotcanvas.view.camera.pan_button_setting = pan_button
  6131. self.mm = self.plotcanvas.graph_event_connect('mouse_move', self.on_mouse_move_over_plot)
  6132. self.mp = self.plotcanvas.graph_event_connect('mouse_press', self.on_mouse_click_over_plot)
  6133. self.mr = self.plotcanvas.graph_event_connect('mouse_release', self.on_mouse_click_release_over_plot)
  6134. self.mdc = self.plotcanvas.graph_event_connect('mouse_double_click', self.on_mouse_double_click_over_plot)
  6135. # Keys over plot enabled
  6136. self.kp = self.plotcanvas.graph_event_connect('key_press', self.ui.keyPressEvent)
  6137. if self.defaults['global_cursor_type'] == 'small':
  6138. self.app_cursor = self.plotcanvas.new_cursor()
  6139. else:
  6140. self.app_cursor = self.plotcanvas.new_cursor(big=True)
  6141. if self.ui.grid_snap_btn.isChecked():
  6142. self.app_cursor.enabled = True
  6143. else:
  6144. self.app_cursor.enabled = False
  6145. if self.is_legacy is False:
  6146. self.hover_shapes = ShapeCollection(parent=self.plotcanvas.view.scene, layers=1)
  6147. else:
  6148. # will use the default Matplotlib axes
  6149. self.hover_shapes = ShapeCollectionLegacy(obj=self, app=self, name='hover')
  6150. def on_zoom_fit(self):
  6151. """
  6152. Callback for zoom-fit request. This can be either from the corresponding
  6153. toolbar button or the '1' key when the canvas is focused. Calls ``self.adjust_axes()``
  6154. with axes limits from the geometry bounds of all objects.
  6155. :return: None
  6156. """
  6157. if self.is_legacy is False:
  6158. self.plotcanvas.fit_view()
  6159. else:
  6160. xmin, ymin, xmax, ymax = self.collection.get_bounds()
  6161. width = xmax - xmin
  6162. height = ymax - ymin
  6163. xmin -= 0.05 * width
  6164. xmax += 0.05 * width
  6165. ymin -= 0.05 * height
  6166. ymax += 0.05 * height
  6167. self.plotcanvas.adjust_axes(xmin, ymin, xmax, ymax)
  6168. def on_zoom_in(self):
  6169. """
  6170. Callback for zoom-in request.
  6171. :return:
  6172. """
  6173. self.plotcanvas.zoom(1 / float(self.defaults['global_zoom_ratio']))
  6174. def on_zoom_out(self):
  6175. """
  6176. Callback for zoom-out request.
  6177. :return:
  6178. """
  6179. self.plotcanvas.zoom(float(self.defaults['global_zoom_ratio']))
  6180. def disable_all_plots(self):
  6181. self.defaults.report_usage("disable_all_plots()")
  6182. self.disable_plots(self.collection.get_list())
  6183. self.inform.emit('[success] %s' %
  6184. _("All plots disabled."))
  6185. def disable_other_plots(self):
  6186. self.defaults.report_usage("disable_other_plots()")
  6187. self.disable_plots(self.collection.get_non_selected())
  6188. self.inform.emit('[success] %s' %
  6189. _("All non selected plots disabled."))
  6190. def enable_all_plots(self):
  6191. self.defaults.report_usage("enable_all_plots()")
  6192. self.enable_plots(self.collection.get_list())
  6193. self.inform.emit('[success] %s' %
  6194. _("All plots enabled."))
  6195. def on_enable_sel_plots(self):
  6196. log.debug("App.on_enable_sel_plot()")
  6197. object_list = self.collection.get_selected()
  6198. self.enable_plots(objects=object_list)
  6199. self.inform.emit('[success] %s' % _("Selected plots enabled..."))
  6200. def on_disable_sel_plots(self):
  6201. log.debug("App.on_disable_sel_plot()")
  6202. # self.inform.emit(_("Disabling plots ..."))
  6203. object_list = self.collection.get_selected()
  6204. self.disable_plots(objects=object_list)
  6205. self.inform.emit('[success] %s' % _("Selected plots disabled..."))
  6206. def enable_plots(self, objects):
  6207. """
  6208. Enable plots
  6209. :param objects: list of Objects to be enabled
  6210. :return:
  6211. """
  6212. log.debug("Enabling plots ...")
  6213. # self.inform.emit(_("Working ..."))
  6214. for obj in objects:
  6215. if obj.options['plot'] is False:
  6216. obj.options.set_change_callback(lambda x: None)
  6217. obj.options['plot'] = True
  6218. try:
  6219. # only the Gerber obj has on_plot_cb_click() method
  6220. obj.ui.plot_cb.stateChanged.disconnect(obj.on_plot_cb_click)
  6221. # disable this cb while disconnected,
  6222. # in case the operation takes time the user is not allowed to change it
  6223. obj.ui.plot_cb.setDisabled(True)
  6224. except AttributeError:
  6225. pass
  6226. obj.set_form_item("plot")
  6227. try:
  6228. obj.ui.plot_cb.stateChanged.connect(obj.on_plot_cb_click)
  6229. obj.ui.plot_cb.setDisabled(False)
  6230. except AttributeError:
  6231. pass
  6232. obj.options.set_change_callback(obj.on_options_change)
  6233. def worker_task(objs):
  6234. with self.proc_container.new(_("Enabling plots ...")):
  6235. for plot_obj in objs:
  6236. # obj.options['plot'] = True
  6237. if isinstance(plot_obj, CNCJobObject):
  6238. plot_obj.plot(visible=True, kind=self.defaults["cncjob_plot_kind"])
  6239. else:
  6240. plot_obj.plot(visible=True)
  6241. self.worker_task.emit({'fcn': worker_task, 'params': [objects]})
  6242. def disable_plots(self, objects):
  6243. """
  6244. Disables plots
  6245. :param objects: list of Objects to be disabled
  6246. :return:
  6247. """
  6248. # if no objects selected then do nothing
  6249. if not self.collection.get_selected():
  6250. return
  6251. log.debug("Disabling plots ...")
  6252. # self.inform.emit(_("Working ..."))
  6253. for obj in objects:
  6254. if obj.options['plot'] is True:
  6255. obj.options.set_change_callback(lambda x: None)
  6256. obj.options['plot'] = False
  6257. try:
  6258. # only the Gerber obj has on_plot_cb_click() method
  6259. obj.ui.plot_cb.stateChanged.disconnect(obj.on_plot_cb_click)
  6260. obj.ui.plot_cb.setDisabled(True)
  6261. except AttributeError:
  6262. pass
  6263. obj.set_form_item("plot")
  6264. try:
  6265. obj.ui.plot_cb.stateChanged.connect(obj.on_plot_cb_click)
  6266. obj.ui.plot_cb.setDisabled(False)
  6267. except AttributeError:
  6268. pass
  6269. obj.options.set_change_callback(obj.on_options_change)
  6270. try:
  6271. self.delete_selection_shape()
  6272. except Exception as e:
  6273. log.debug("App.disable_plots() --> %s" % str(e))
  6274. def worker_task(objs):
  6275. with self.proc_container.new(_("Disabling plots ...")):
  6276. for plot_obj in objs:
  6277. # obj.options['plot'] = True
  6278. if isinstance(plot_obj, CNCJobObject):
  6279. plot_obj.plot(visible=False, kind=self.defaults["cncjob_plot_kind"])
  6280. else:
  6281. plot_obj.plot(visible=False)
  6282. self.worker_task.emit({'fcn': worker_task, 'params': [objects]})
  6283. def toggle_plots(self, objects):
  6284. """
  6285. Toggle plots visibility
  6286. :param objects: list of Objects for which to be toggled the visibility
  6287. :return: None
  6288. """
  6289. # if no objects selected then do nothing
  6290. if not self.collection.get_selected():
  6291. return
  6292. log.debug("Toggling plots ...")
  6293. self.inform.emit(_("Working ..."))
  6294. for obj in objects:
  6295. if obj.options['plot'] is False:
  6296. obj.options['plot'] = True
  6297. else:
  6298. obj.options['plot'] = False
  6299. self.app_obj.plots_updated.emit()
  6300. def clear_plots(self):
  6301. """
  6302. Clear the plots
  6303. :return: None
  6304. """
  6305. objects = self.collection.get_list()
  6306. for obj in objects:
  6307. obj.clear(obj == objects[-1])
  6308. # Clear pool to free memory
  6309. self.clear_pool()
  6310. def on_set_color_action_triggered(self):
  6311. """
  6312. This slot gets called by clicking on the menu entry in the Set Color submenu of the context menu in Project Tab
  6313. :return:
  6314. """
  6315. new_color = self.defaults['gerber_plot_fill']
  6316. clicked_action = self.sender()
  6317. assert isinstance(clicked_action, QAction), "Expected a QAction, got %s" % type(clicked_action)
  6318. act_name = clicked_action.text()
  6319. sel_obj_list = self.collection.get_selected()
  6320. if not sel_obj_list:
  6321. return
  6322. # a default value, I just chose this one
  6323. alpha_level = 'BF'
  6324. for sel_obj in sel_obj_list:
  6325. if sel_obj.kind == 'excellon':
  6326. alpha_level = str(hex(
  6327. self.ui.excellon_defaults_form.excellon_gen_group.excellon_alpha_entry.get_value())[2:])
  6328. elif sel_obj.kind == 'gerber':
  6329. alpha_level = str(hex(self.ui.gerber_defaults_form.gerber_gen_group.gerber_alpha_entry.get_value())[2:])
  6330. elif sel_obj.kind == 'geometry':
  6331. alpha_level = 'FF'
  6332. else:
  6333. log.debug(
  6334. "App.on_set_color_action_triggered() --> Default alpfa for this object type not supported yet")
  6335. continue
  6336. sel_obj.alpha_level = alpha_level
  6337. if act_name == _('Red'):
  6338. new_color = '#FF0000' + alpha_level
  6339. if act_name == _('Blue'):
  6340. new_color = '#0000FF' + alpha_level
  6341. if act_name == _('Yellow'):
  6342. new_color = '#FFDF00' + alpha_level
  6343. if act_name == _('Green'):
  6344. new_color = '#00FF00' + alpha_level
  6345. if act_name == _('Purple'):
  6346. new_color = '#FF00FF' + alpha_level
  6347. if act_name == _('Brown'):
  6348. new_color = '#A52A2A' + alpha_level
  6349. if act_name == _('White'):
  6350. new_color = '#FFFFFF' + alpha_level
  6351. if act_name == _('Black'):
  6352. new_color = '#000000' + alpha_level
  6353. if act_name == _('Custom'):
  6354. new_color = QtGui.QColor(self.defaults['gerber_plot_fill'][:7])
  6355. c_dialog = QtWidgets.QColorDialog()
  6356. plot_fill_color = c_dialog.getColor(initial=new_color)
  6357. if plot_fill_color.isValid() is False:
  6358. return
  6359. new_color = str(plot_fill_color.name()) + alpha_level
  6360. if act_name == _("Default"):
  6361. for sel_obj in sel_obj_list:
  6362. if sel_obj.kind == 'excellon':
  6363. new_color = self.defaults['excellon_plot_fill']
  6364. new_line_color = self.defaults['excellon_plot_line']
  6365. elif sel_obj.kind == 'gerber':
  6366. new_color = self.defaults['gerber_plot_fill']
  6367. new_line_color = self.defaults['gerber_plot_line']
  6368. elif sel_obj.kind == 'geometry':
  6369. new_color = self.defaults['geometry_plot_line']
  6370. new_line_color = self.defaults['geometry_plot_line']
  6371. else:
  6372. log.debug(
  6373. "App.on_set_color_action_triggered() --> Default color for this object type not supported yet")
  6374. continue
  6375. sel_obj.fill_color = new_color
  6376. sel_obj.outline_color = new_line_color
  6377. sel_obj.shapes.redraw(
  6378. update_colors=(new_color, new_line_color)
  6379. )
  6380. return
  6381. if act_name == _("Opacity"):
  6382. # alpha_level, ok_button = QtWidgets.QInputDialog.getInt(
  6383. # self.ui, _("Set alpha level ..."), '%s:' % _("Value"), min=0, max=255, step=1, value=191)
  6384. alpha_dialog = FCInputDialogSlider(
  6385. self.ui, _("Set alpha level ..."), '%s:' % _("Value"), min=0, max=255, step=1, init_val=191)
  6386. alpha_level, ok_button = alpha_dialog.get_results()
  6387. if ok_button:
  6388. alpha_str = str(hex(alpha_level)[2:]) if alpha_level != 0 else '00'
  6389. for sel_obj in sel_obj_list:
  6390. sel_obj.fill_color = sel_obj.fill_color[:-2] + alpha_str
  6391. sel_obj.shapes.redraw(
  6392. update_colors=(sel_obj.fill_color, sel_obj.outline_color)
  6393. )
  6394. return
  6395. new_line_color = color_variant(new_color[:7], 0.7)
  6396. if act_name == _("White"):
  6397. new_line_color = color_variant("#dedede", 0.7)
  6398. for sel_obj in sel_obj_list:
  6399. sel_obj.fill_color = new_color
  6400. sel_obj.outline_color = new_line_color
  6401. sel_obj.shapes.redraw(
  6402. update_colors=(new_color, new_line_color)
  6403. )
  6404. # make sure to set the color in the Gerber colors storage self.defaults["gerber_color_list"]
  6405. group = self.collection.group_items["gerber"]
  6406. group_index = self.collection.index(group.row(), 0, QtCore.QModelIndex())
  6407. new_c = (new_line_color, new_color)
  6408. for sel_obj in sel_obj_list:
  6409. if sel_obj.kind == 'gerber':
  6410. item = sel_obj.item
  6411. item_index = self.collection.index(item.row(), 0, group_index)
  6412. idx = item_index.row()
  6413. self.defaults["gerber_color_list"][idx] = new_c
  6414. def generate_cnc_job(self, objects):
  6415. """
  6416. Slot that will be called by clicking an entry in the contextual menu generated in the Project Tab tree
  6417. :param objects: Selected objects in the Project Tab
  6418. :return:
  6419. """
  6420. self.defaults.report_usage("generate_cnc_job()")
  6421. # for obj in objects:
  6422. # obj.generatecncjob()
  6423. for obj in objects:
  6424. obj.on_generatecnc_button_click()
  6425. def start_delayed_quit(self, delay, filename, should_quit=None):
  6426. """
  6427. :param delay: period of checking if project file size is more than zero; in seconds
  6428. :param filename: the name of the project file to be checked periodically for size more than zero
  6429. :param should_quit: if the task finished will be followed by an app quit; boolean
  6430. :return:
  6431. """
  6432. to_quit = should_quit
  6433. self.save_timer = QtCore.QTimer()
  6434. self.save_timer.setInterval(delay)
  6435. self.save_timer.timeout.connect(lambda: self.check_project_file_size(filename=filename, should_quit=to_quit))
  6436. self.save_timer.start()
  6437. def check_project_file_size(self, filename, should_quit=None):
  6438. """
  6439. :param filename: the name of the project file to be checked periodically for size more than zero
  6440. :param should_quit: will quit the app if True; boolean
  6441. :return:
  6442. """
  6443. try:
  6444. if os.stat(filename).st_size > 0:
  6445. self.save_in_progress = False
  6446. self.save_timer.stop()
  6447. if should_quit:
  6448. self.app_quit.emit()
  6449. except Exception:
  6450. traceback.print_exc()
  6451. def save_project_auto(self):
  6452. """
  6453. Called periodically to save the project.
  6454. 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
  6455. # progress.
  6456. :return:
  6457. """
  6458. if self.block_autosave is False and self.should_we_save is True and self.save_in_progress is False:
  6459. self.on_file_saveproject()
  6460. def save_project_auto_update(self):
  6461. """
  6462. Update the auto save time interval value.
  6463. :return:
  6464. """
  6465. log.debug("App.save_project_auto_update() --> updated the interval timeout.")
  6466. try:
  6467. if self.autosave_timer.isActive():
  6468. self.autosave_timer.stop()
  6469. except Exception:
  6470. pass
  6471. if self.defaults['global_autosave'] is True:
  6472. self.autosave_timer.setInterval(int(self.defaults['global_autosave_timeout']))
  6473. self.autosave_timer.start()
  6474. def on_options_app2project(self):
  6475. """
  6476. Callback for Options->Transfer Options->App=>Project. Copies options
  6477. from application defaults to project defaults.
  6478. :return: None
  6479. """
  6480. self.defaults.report_usage("on_options_app2project")
  6481. self.preferencesUiManager.defaults_read_form()
  6482. self.options.update(self.defaults)
  6483. def shell_message(self, msg, show=False, error=False, warning=False, success=False, selected=False, new_line=True):
  6484. """
  6485. Shows a message on the FlatCAM Shell
  6486. :param msg: Message to display.
  6487. :param show: Opens the shell.
  6488. :param error: Shows the message as an error.
  6489. :param warning: Shows the message as an warning.
  6490. :param success: Shows the message as an success.
  6491. :param selected: Indicate that something was selected on canvas
  6492. :return: None
  6493. """
  6494. end = '\n' if new_line is True else ''
  6495. if show:
  6496. self.ui.shell_dock.show()
  6497. try:
  6498. if error:
  6499. self.shell.append_error(msg + end)
  6500. elif warning:
  6501. self.shell.append_warning(msg + end)
  6502. elif success:
  6503. self.shell.append_success(msg + end)
  6504. elif selected:
  6505. self.shell.append_selected(msg + end)
  6506. else:
  6507. self.shell.append_output(msg + end)
  6508. except AttributeError:
  6509. log.debug("shell_message() is called before Shell Class is instantiated. The message is: %s", str(msg))
  6510. def dec_format(self, val, dec=None):
  6511. """
  6512. Returns a formatted float value with a certain number of decimals
  6513. """
  6514. dec_nr = dec if dec is not None else self.decimals
  6515. return float('%.*f' % (dec_nr, val))
  6516. class ArgsThread(QtCore.QObject):
  6517. open_signal = pyqtSignal(list)
  6518. start = pyqtSignal()
  6519. stop = pyqtSignal()
  6520. if sys.platform == 'win32':
  6521. address = (r'\\.\pipe\NPtest', 'AF_PIPE')
  6522. else:
  6523. address = ('/tmp/testipc', 'AF_UNIX')
  6524. def __init__(self):
  6525. super().__init__()
  6526. self.listener = None
  6527. self.thread_exit = False
  6528. self.start.connect(self.run)
  6529. self.stop.connect(self.close_listener)
  6530. def my_loop(self, address):
  6531. try:
  6532. self.listener = Listener(*address)
  6533. while self.thread_exit is False:
  6534. conn = self.listener.accept()
  6535. self.serve(conn)
  6536. except socket.error:
  6537. try:
  6538. conn = Client(*address)
  6539. conn.send(sys.argv)
  6540. conn.send('close')
  6541. # close the current instance only if there are args
  6542. if len(sys.argv) > 1:
  6543. try:
  6544. self.listener.close()
  6545. except Exception:
  6546. pass
  6547. sys.exit()
  6548. except ConnectionRefusedError:
  6549. if sys.platform == 'win32':
  6550. pass
  6551. else:
  6552. os.system('rm /tmp/testipc')
  6553. self.listener = Listener(*address)
  6554. while True:
  6555. conn = self.listener.accept()
  6556. self.serve(conn)
  6557. def serve(self, conn):
  6558. while self.thread_exit is False:
  6559. msg = conn.recv()
  6560. if msg == 'close':
  6561. break
  6562. self.open_signal.emit(msg)
  6563. conn.close()
  6564. # the decorator is a must; without it this technique will not work unless the start signal is connected
  6565. # in the main thread (where this class is instantiated) after the instance is moved o the new thread
  6566. @pyqtSlot()
  6567. def run(self):
  6568. self.my_loop(self.address)
  6569. @pyqtSlot()
  6570. def close_listener(self):
  6571. self.thread_exit = True
  6572. self.listener.close()
  6573. class MenuFileHandlers(QtCore.QObject):
  6574. def __init__(self, app):
  6575. super().__init__()
  6576. self.app = app
  6577. self.inform = self.app.inform
  6578. self.splash = self.app.splash
  6579. self.worker_task = self.app.worker_task
  6580. self.defaults = self.app.defaults
  6581. def on_fileopengerber(self, signal, name=None):
  6582. """
  6583. File menu callback for opening a Gerber.
  6584. :param signal: required because clicking the entry will generate a checked signal which needs a container
  6585. :param name:
  6586. :return: None
  6587. """
  6588. self.app.log.debug("on_fileopengerber()")
  6589. _filter_ = "Gerber Files (*.gbr *.ger *.gtl *.gbl *.gts *.gbs *.gtp *.gbp *.gto *.gbo *.gm1 *.gml *.gm3 " \
  6590. "*.gko *.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim *.mil *.grb " \
  6591. "*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb *.pho *.gdo *.art *.gbd *.outline);;" \
  6592. "Protel Files (*.gtl *.gbl *.gts *.gbs *.gto *.gbo *.gtp *.gbp *.gml *.gm1 *.gm3 *.gko " \
  6593. "*.outline);;" \
  6594. "Eagle Files (*.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim " \
  6595. "*.mil);;" \
  6596. "OrCAD Files (*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb);;" \
  6597. "Allegro Files (*.art);;" \
  6598. "Mentor Files (*.pho *.gdo);;" \
  6599. "All Files (*.*)"
  6600. if name is None:
  6601. try:
  6602. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Gerber"),
  6603. directory=self.app.get_last_folder(),
  6604. filter=_filter_,
  6605. initialFilter=self.app.last_op_gerber_filter)
  6606. except TypeError:
  6607. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Gerber"), filter=_filter_)
  6608. filenames = [str(filename) for filename in filenames]
  6609. self.app.last_op_gerber_filter = _f
  6610. else:
  6611. filenames = [name]
  6612. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  6613. "Canvas initialization finished in"),
  6614. '%.2f' % self.app.used_time,
  6615. _("Opening Gerber file.")),
  6616. alignment=Qt.AlignBottom | Qt.AlignLeft,
  6617. color=QtGui.QColor("gray"))
  6618. if len(filenames) == 0:
  6619. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6620. else:
  6621. for filename in filenames:
  6622. if filename != '':
  6623. self.worker_task.emit({'fcn': self.open_gerber, 'params': [filename]})
  6624. def on_fileopenexcellon(self, signal, name=None):
  6625. """
  6626. File menu callback for opening an Excellon file.
  6627. :param signal: required because clicking the entry will generate a checked signal which needs a container
  6628. :param name:
  6629. :return: None
  6630. """
  6631. self.app.log.debug("on_fileopenexcellon()")
  6632. _filter_ = "Excellon Files (*.drl *.txt *.xln *.drd *.tap *.exc *.ncd);;" \
  6633. "All Files (*.*)"
  6634. if name is None:
  6635. try:
  6636. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Excellon"),
  6637. directory=self.app.get_last_folder(),
  6638. filter=_filter_,
  6639. initialFilter=self.app.last_op_excellon_filter)
  6640. except TypeError:
  6641. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Excellon"), filter=_filter_)
  6642. filenames = [str(filename) for filename in filenames]
  6643. self.app.last_op_excellon_filter = _f
  6644. else:
  6645. filenames = [str(name)]
  6646. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  6647. "Canvas initialization finished in"),
  6648. '%.2f' % self.app.used_time,
  6649. _("Opening Excellon file.")),
  6650. alignment=Qt.AlignBottom | Qt.AlignLeft,
  6651. color=QtGui.QColor("gray"))
  6652. if len(filenames) == 0:
  6653. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6654. else:
  6655. for filename in filenames:
  6656. if filename != '':
  6657. self.worker_task.emit({'fcn': self.open_excellon, 'params': [filename]})
  6658. def on_fileopengcode(self, signal, name=None):
  6659. """
  6660. File menu call back for opening gcode.
  6661. :param signal: required because clicking the entry will generate a checked signal which needs a container
  6662. :param name:
  6663. :return:
  6664. """
  6665. self.app.log.debug("on_fileopengcode()")
  6666. # https://bobcadsupport.com/helpdesk/index.php?/Knowledgebase/Article/View/13/5/known-g-code-file-extensions
  6667. _filter_ = "G-Code Files (*.txt *.nc *.ncc *.tap *.gcode *.cnc *.ecs *.fnc *.dnc *.ncg *.gc *.fan *.fgc" \
  6668. " *.din *.xpi *.hnc *.h *.i *.ncp *.min *.gcd *.rol *.mpr *.ply *.out *.eia *.sbp *.mpf);;" \
  6669. "All Files (*.*)"
  6670. if name is None:
  6671. try:
  6672. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open G-Code"),
  6673. directory=self.app.get_last_folder(),
  6674. filter=_filter_,
  6675. initialFilter=self.app.last_op_gcode_filter)
  6676. except TypeError:
  6677. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open G-Code"), filter=_filter_)
  6678. filenames = [str(filename) for filename in filenames]
  6679. self.app.last_op_gcode_filter = _f
  6680. else:
  6681. filenames = [name]
  6682. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  6683. "Canvas initialization finished in"),
  6684. '%.2f' % self.app.used_time,
  6685. _("Opening G-Code file.")),
  6686. alignment=Qt.AlignBottom | Qt.AlignLeft,
  6687. color=QtGui.QColor("gray"))
  6688. if len(filenames) == 0:
  6689. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6690. else:
  6691. for filename in filenames:
  6692. if filename != '':
  6693. self.worker_task.emit({'fcn': self.open_gcode, 'params': [filename, None, True]})
  6694. def on_file_openproject(self, signal):
  6695. """
  6696. File menu callback for opening a project.
  6697. :param signal: required because clicking the entry will generate a checked signal which needs a container
  6698. :return: None
  6699. """
  6700. self.app.log.debug("on_file_openproject()")
  6701. _filter_ = "FlatCAM Project (*.FlatPrj);;All Files (*.*)"
  6702. try:
  6703. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Project"),
  6704. directory=self.app.get_last_folder(), filter=_filter_)
  6705. except TypeError:
  6706. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Project"), filter=_filter_)
  6707. filename = str(filename)
  6708. if filename == "":
  6709. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6710. else:
  6711. # self.worker_task.emit({'fcn': self.open_project,
  6712. # 'params': [filename]})
  6713. # The above was failing because open_project() is not
  6714. # thread safe. The new_project()
  6715. self.open_project(filename)
  6716. def on_fileopenhpgl2(self, signal, name=None):
  6717. """
  6718. File menu callback for opening a HPGL2.
  6719. :param signal: required because clicking the entry will generate a checked signal which needs a container
  6720. :param name:
  6721. :return: None
  6722. """
  6723. self.app.log.debug("on_fileopenhpgl2()")
  6724. _filter_ = "HPGL2 Files (*.plt);;" \
  6725. "All Files (*.*)"
  6726. if name is None:
  6727. try:
  6728. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open HPGL2"),
  6729. directory=self.app.get_last_folder(),
  6730. filter=_filter_)
  6731. except TypeError:
  6732. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open HPGL2"), filter=_filter_)
  6733. filenames = [str(filename) for filename in filenames]
  6734. else:
  6735. filenames = [name]
  6736. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  6737. "Canvas initialization finished in"),
  6738. '%.2f' % self.app.used_time,
  6739. _("Opening HPGL2 file.")),
  6740. alignment=Qt.AlignBottom | Qt.AlignLeft,
  6741. color=QtGui.QColor("gray"))
  6742. if len(filenames) == 0:
  6743. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6744. else:
  6745. for filename in filenames:
  6746. if filename != '':
  6747. self.worker_task.emit({'fcn': self.open_hpgl2, 'params': [filename]})
  6748. def on_file_openconfig(self, signal):
  6749. """
  6750. File menu callback for opening a config file.
  6751. :param signal: required because clicking the entry will generate a checked signal which needs a container
  6752. :return: None
  6753. """
  6754. self.app.log.debug("on_file_openconfig()")
  6755. _filter_ = "FlatCAM Config (*.FlatConfig);;FlatCAM Config (*.json);;All Files (*.*)"
  6756. try:
  6757. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Configuration File"),
  6758. directory=self.app.data_path, filter=_filter_)
  6759. except TypeError:
  6760. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Configuration File"),
  6761. filter=_filter_)
  6762. if filename == "":
  6763. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6764. else:
  6765. self.open_config_file(filename)
  6766. def on_file_exportsvg(self):
  6767. """
  6768. Callback for menu item File->Export SVG.
  6769. :return: None
  6770. """
  6771. self.app.log.debug("on_file_exportsvg()")
  6772. obj = self.app.collection.get_active()
  6773. if obj is None:
  6774. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6775. msg = _("Please Select a Geometry object to export")
  6776. msgbox = QtWidgets.QMessageBox()
  6777. msgbox.setIcon(QtWidgets.QMessageBox.Warning)
  6778. msgbox.setInformativeText(msg)
  6779. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  6780. msgbox.setDefaultButton(bt_ok)
  6781. msgbox.exec_()
  6782. return
  6783. # Check for more compatible types and add as required
  6784. if (not isinstance(obj, GeometryObject)
  6785. and not isinstance(obj, GerberObject)
  6786. and not isinstance(obj, CNCJobObject)
  6787. and not isinstance(obj, ExcellonObject)):
  6788. msg = '[ERROR_NOTCL] %s' % _("Only Geometry, Gerber and CNCJob objects can be used.")
  6789. msgbox = QtWidgets.QMessageBox()
  6790. msgbox.setIcon(QtWidgets.QMessageBox.Warning)
  6791. msgbox.setInformativeText(msg)
  6792. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  6793. msgbox.setDefaultButton(bt_ok)
  6794. msgbox.exec_()
  6795. return
  6796. name = obj.options["name"]
  6797. _filter = "SVG File (*.svg);;All Files (*.*)"
  6798. try:
  6799. filename, _f = FCFileSaveDialog.get_saved_filename(
  6800. caption=_("Export SVG"),
  6801. directory=self.app.get_last_save_folder() + '/' + str(name) + '_svg',
  6802. ext_filter=_filter)
  6803. except TypeError:
  6804. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export SVG"), ext_filter=_filter)
  6805. filename = str(filename)
  6806. if filename == "":
  6807. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6808. return
  6809. else:
  6810. self.export_svg(name, filename)
  6811. if self.defaults["global_open_style"] is False:
  6812. self.app.file_opened.emit("SVG", filename)
  6813. self.app.file_saved.emit("SVG", filename)
  6814. def on_file_exportpng(self):
  6815. self.app.log.debug("on_file_exportpng()")
  6816. date = str(datetime.today()).rpartition('.')[0]
  6817. date = ''.join(c for c in date if c not in ':-')
  6818. date = self.app.date.replace(' ', '_')
  6819. data = None
  6820. if self.app.is_legacy is False:
  6821. image = _screenshot(alpha=False)
  6822. data = np.asarray(image)
  6823. if not data.ndim == 3 and data.shape[-1] in (3, 4):
  6824. self.inform.emit('[[WARNING_NOTCL]] %s' % _('Data must be a 3D array with last dimension 3 or 4'))
  6825. return
  6826. filter_ = "PNG File (*.png);;All Files (*.*)"
  6827. try:
  6828. filename, _f = FCFileSaveDialog.get_saved_filename(
  6829. caption=_("Export PNG Image"),
  6830. directory=self.app.get_last_save_folder() + '/png_' + date,
  6831. ext_filter=filter_)
  6832. except TypeError:
  6833. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export PNG Image"), ext_filter=filter_)
  6834. filename = str(filename)
  6835. if filename == "":
  6836. self.inform.emit(_("Cancelled."))
  6837. return
  6838. else:
  6839. if self.app.is_legacy is False:
  6840. write_png(filename, data)
  6841. else:
  6842. self.app.plotcanvas.figure.savefig(filename)
  6843. if self.defaults["global_open_style"] is False:
  6844. self.app.file_opened.emit("png", filename)
  6845. self.app.file_saved.emit("png", filename)
  6846. def on_file_savegerber(self):
  6847. """
  6848. Callback for menu item in Project context menu.
  6849. :return: None
  6850. """
  6851. self.app.log.debug("on_file_savegerber()")
  6852. obj = self.app.collection.get_active()
  6853. if obj is None:
  6854. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6855. return
  6856. # Check for more compatible types and add as required
  6857. if not isinstance(obj, GerberObject):
  6858. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Gerber objects can be saved as Gerber files..."))
  6859. return
  6860. name = self.app.collection.get_active().options["name"]
  6861. _filter = "Gerber File (*.GBR);;Gerber File (*.GRB);;All Files (*.*)"
  6862. try:
  6863. filename, _f = FCFileSaveDialog.get_saved_filename(
  6864. caption="Save Gerber source file",
  6865. directory=self.app.get_last_save_folder() + '/' + name,
  6866. ext_filter=_filter)
  6867. except TypeError:
  6868. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Gerber source file"), ext_filter=_filter)
  6869. filename = str(filename)
  6870. if filename == "":
  6871. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6872. return
  6873. else:
  6874. self.save_source_file(name, filename)
  6875. if self.defaults["global_open_style"] is False:
  6876. self.app.file_opened.emit("Gerber", filename)
  6877. self.app.file_saved.emit("Gerber", filename)
  6878. def on_file_savescript(self):
  6879. """
  6880. Callback for menu item in Project context menu.
  6881. :return: None
  6882. """
  6883. self.app.log.debug("on_file_savescript()")
  6884. obj = self.app.collection.get_active()
  6885. if obj is None:
  6886. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6887. return
  6888. # Check for more compatible types and add as required
  6889. if not isinstance(obj, ScriptObject):
  6890. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Script objects can be saved as TCL Script files..."))
  6891. return
  6892. name = self.app.collection.get_active().options["name"]
  6893. _filter = "FlatCAM Scripts (*.FlatScript);;All Files (*.*)"
  6894. try:
  6895. filename, _f = FCFileSaveDialog.get_saved_filename(
  6896. caption="Save Script source file",
  6897. directory=self.app.get_last_save_folder() + '/' + name,
  6898. ext_filter=_filter)
  6899. except TypeError:
  6900. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Script source file"), ext_filter=_filter)
  6901. filename = str(filename)
  6902. if filename == "":
  6903. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6904. return
  6905. else:
  6906. self.save_source_file(name, filename)
  6907. if self.defaults["global_open_style"] is False:
  6908. self.app.file_opened.emit("Script", filename)
  6909. self.app.file_saved.emit("Script", filename)
  6910. def on_file_savedocument(self):
  6911. """
  6912. Callback for menu item in Project context menu.
  6913. :return: None
  6914. """
  6915. self.app.log.debug("on_file_savedocument()")
  6916. obj = self.app.collection.get_active()
  6917. if obj is None:
  6918. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6919. return
  6920. # Check for more compatible types and add as required
  6921. if not isinstance(obj, ScriptObject):
  6922. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Document objects can be saved as Document files..."))
  6923. return
  6924. name = self.app.collection.get_active().options["name"]
  6925. _filter = "FlatCAM Documents (*.FlatDoc);;All Files (*.*)"
  6926. try:
  6927. filename, _f = FCFileSaveDialog.get_saved_filename(
  6928. caption="Save Document source file",
  6929. directory=self.app.get_last_save_folder() + '/' + name,
  6930. ext_filter=_filter)
  6931. except TypeError:
  6932. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Document source file"),
  6933. ext_filter=_filter)
  6934. filename = str(filename)
  6935. if filename == "":
  6936. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6937. return
  6938. else:
  6939. self.save_source_file(name, filename)
  6940. if self.defaults["global_open_style"] is False:
  6941. self.app.file_opened.emit("Document", filename)
  6942. self.app.file_saved.emit("Document", filename)
  6943. def on_file_saveexcellon(self):
  6944. """
  6945. Callback for menu item in project context menu.
  6946. :return: None
  6947. """
  6948. self.app.log.debug("on_file_saveexcellon()")
  6949. obj = self.app.collection.get_active()
  6950. if obj is None:
  6951. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6952. return
  6953. # Check for more compatible types and add as required
  6954. if not isinstance(obj, ExcellonObject):
  6955. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Excellon objects can be saved as Excellon files..."))
  6956. return
  6957. name = self.app.collection.get_active().options["name"]
  6958. _filter = "Excellon File (*.DRL);;Excellon File (*.TXT);;All Files (*.*)"
  6959. try:
  6960. filename, _f = FCFileSaveDialog.get_saved_filename(
  6961. caption=_("Save Excellon source file"),
  6962. directory=self.app.get_last_save_folder() + '/' + name,
  6963. ext_filter=_filter)
  6964. except TypeError:
  6965. filename, _f = FCFileSaveDialog.get_saved_filename(
  6966. caption=_("Save Excellon source file"), ext_filter=_filter)
  6967. filename = str(filename)
  6968. if filename == "":
  6969. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6970. return
  6971. else:
  6972. self.save_source_file(name, filename)
  6973. if self.defaults["global_open_style"] is False:
  6974. self.app.file_opened.emit("Excellon", filename)
  6975. self.app.file_saved.emit("Excellon", filename)
  6976. def on_file_exportexcellon(self):
  6977. """
  6978. Callback for menu item File->Export->Excellon.
  6979. :return: None
  6980. """
  6981. self.app.log.debug("on_file_exportexcellon()")
  6982. obj = self.app.collection.get_active()
  6983. if obj is None:
  6984. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6985. return
  6986. # Check for more compatible types and add as required
  6987. if not isinstance(obj, ExcellonObject):
  6988. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Excellon objects can be saved as Excellon files..."))
  6989. return
  6990. name = self.app.collection.get_active().options["name"]
  6991. _filter = self.defaults["excellon_save_filters"]
  6992. try:
  6993. filename, _f = FCFileSaveDialog.get_saved_filename(
  6994. caption=_("Export Excellon"),
  6995. directory=self.app.get_last_save_folder() + '/' + name,
  6996. ext_filter=_filter)
  6997. except TypeError:
  6998. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export Excellon"), ext_filter=_filter)
  6999. filename = str(filename)
  7000. if filename == "":
  7001. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  7002. return
  7003. else:
  7004. used_extension = filename.rpartition('.')[2]
  7005. obj.update_filters(last_ext=used_extension, filter_string='excellon_save_filters')
  7006. self.export_excellon(name, filename)
  7007. if self.defaults["global_open_style"] is False:
  7008. self.app.file_opened.emit("Excellon", filename)
  7009. self.app.file_saved.emit("Excellon", filename)
  7010. def on_file_exportgerber(self):
  7011. """
  7012. Callback for menu item File->Export->Gerber.
  7013. :return: None
  7014. """
  7015. App.log.debug("on_file_exportgerber()")
  7016. obj = self.app.collection.get_active()
  7017. if obj is None:
  7018. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  7019. return
  7020. # Check for more compatible types and add as required
  7021. if not isinstance(obj, GerberObject):
  7022. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Gerber objects can be saved as Gerber files..."))
  7023. return
  7024. name = self.app.collection.get_active().options["name"]
  7025. _filter_ = self.defaults['gerber_save_filters']
  7026. try:
  7027. filename, _f = FCFileSaveDialog.get_saved_filename(
  7028. caption=_("Export Gerber"),
  7029. directory=self.app.get_last_save_folder() + '/' + name,
  7030. ext_filter=_filter_)
  7031. except TypeError:
  7032. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export Gerber"), ext_filter=_filter_)
  7033. filename = str(filename)
  7034. if filename == "":
  7035. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  7036. return
  7037. else:
  7038. used_extension = filename.rpartition('.')[2]
  7039. obj.update_filters(last_ext=used_extension, filter_string='gerber_save_filters')
  7040. self.export_gerber(name, filename)
  7041. if self.defaults["global_open_style"] is False:
  7042. self.app.file_opened.emit("Gerber", filename)
  7043. self.app.file_saved.emit("Gerber", filename)
  7044. def on_file_exportdxf(self):
  7045. """
  7046. Callback for menu item File->Export DXF.
  7047. :return: None
  7048. """
  7049. App.log.debug("on_file_exportdxf()")
  7050. obj = self.app.collection.get_active()
  7051. if obj is None:
  7052. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  7053. msg = _("Please Select a Geometry object to export")
  7054. msgbox = QtWidgets.QMessageBox()
  7055. msgbox.setIcon(QtWidgets.QMessageBox.Warning)
  7056. msgbox.setInformativeText(msg)
  7057. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  7058. msgbox.setDefaultButton(bt_ok)
  7059. msgbox.exec_()
  7060. return
  7061. # Check for more compatible types and add as required
  7062. if not isinstance(obj, GeometryObject):
  7063. msg = '[ERROR_NOTCL] %s' % _("Only Geometry objects can be used.")
  7064. msgbox = QtWidgets.QMessageBox()
  7065. msgbox.setIcon(QtWidgets.QMessageBox.Warning)
  7066. msgbox.setInformativeText(msg)
  7067. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  7068. msgbox.setDefaultButton(bt_ok)
  7069. msgbox.exec_()
  7070. return
  7071. name = self.app.collection.get_active().options["name"]
  7072. _filter_ = "DXF File .dxf (*.DXF);;All Files (*.*)"
  7073. try:
  7074. filename, _f = FCFileSaveDialog.get_saved_filename(
  7075. caption=_("Export DXF"),
  7076. directory=self.app.get_last_save_folder() + '/' + name,
  7077. ext_filter=_filter_)
  7078. except TypeError:
  7079. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export DXF"), ext_filter=_filter_)
  7080. filename = str(filename)
  7081. if filename == "":
  7082. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  7083. return
  7084. else:
  7085. self.export_dxf(name, filename)
  7086. if self.defaults["global_open_style"] is False:
  7087. self.app.file_opened.emit("DXF", filename)
  7088. self.app.file_saved.emit("DXF", filename)
  7089. def on_file_importsvg(self, type_of_obj):
  7090. """
  7091. Callback for menu item File->Import SVG.
  7092. :param type_of_obj: to import the SVG as Geometry or as Gerber
  7093. :type type_of_obj: str
  7094. :return: None
  7095. """
  7096. self.app.log.debug("on_file_importsvg()")
  7097. _filter_ = "SVG File .svg (*.svg);;All Files (*.*)"
  7098. try:
  7099. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import SVG"),
  7100. directory=self.app.get_last_folder(),
  7101. filter=_filter_)
  7102. except TypeError:
  7103. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import SVG"),
  7104. filter=_filter_)
  7105. if type_of_obj != "geometry" and type_of_obj != "gerber":
  7106. type_of_obj = "geometry"
  7107. filenames = [str(filename) for filename in filenames]
  7108. if len(filenames) == 0:
  7109. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  7110. else:
  7111. for filename in filenames:
  7112. if filename != '':
  7113. self.worker_task.emit({'fcn': self.import_svg, 'params': [filename, type_of_obj]})
  7114. def on_file_importdxf(self, type_of_obj):
  7115. """
  7116. Callback for menu item File->Import DXF.
  7117. :param type_of_obj: to import the DXF as Geometry or as Gerber
  7118. :type type_of_obj: str
  7119. :return: None
  7120. """
  7121. self.app.log.debug("on_file_importdxf()")
  7122. _filter_ = "DXF File .dxf (*.DXF);;All Files (*.*)"
  7123. try:
  7124. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import DXF"),
  7125. directory=self.app.get_last_folder(),
  7126. filter=_filter_)
  7127. except TypeError:
  7128. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import DXF"),
  7129. filter=_filter_)
  7130. if type_of_obj != "geometry" and type_of_obj != "gerber":
  7131. type_of_obj = "geometry"
  7132. filenames = [str(filename) for filename in filenames]
  7133. if len(filenames) == 0:
  7134. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  7135. else:
  7136. for filename in filenames:
  7137. if filename != '':
  7138. self.worker_task.emit({'fcn': self.import_dxf, 'params': [filename, type_of_obj]})
  7139. def on_file_new_click(self):
  7140. """
  7141. Callback for menu item File -> New.
  7142. Executed on clicking the Menu -> File -> New Project
  7143. :return:
  7144. """
  7145. if self.app.collection.get_list() and self.app.should_we_save:
  7146. msgbox = QtWidgets.QMessageBox()
  7147. # msgbox.setText("<B>Save changes ...</B>")
  7148. msgbox.setText(_("There are files/objects opened in FlatCAM.\n"
  7149. "Creating a New project will delete them.\n"
  7150. "Do you want to Save the project?"))
  7151. msgbox.setWindowTitle(_("Save changes"))
  7152. msgbox.setWindowIcon(QtGui.QIcon(self.app.resource_location + '/save_as.png'))
  7153. msgbox.setIcon(QtWidgets.QMessageBox.Question)
  7154. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  7155. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  7156. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  7157. msgbox.setDefaultButton(bt_yes)
  7158. msgbox.exec_()
  7159. response = msgbox.clickedButton()
  7160. if response == bt_yes:
  7161. self.on_file_saveprojectas()
  7162. elif response == bt_cancel:
  7163. return
  7164. elif response == bt_no:
  7165. self.on_file_new()
  7166. else:
  7167. self.on_file_new()
  7168. self.inform.emit('[success] %s...' % _("New Project created"))
  7169. def on_file_new(self, cli=None):
  7170. """
  7171. Returns the application to its startup state. This method is thread-safe.
  7172. :param cli: Boolean. If True this method was run from command line
  7173. :return: None
  7174. """
  7175. self.defaults.report_usage("on_file_new")
  7176. # Remove everything from memory
  7177. self.app.log.debug("on_file_new()")
  7178. # close any editor that might be open
  7179. if self.app.call_source != 'app':
  7180. self.app.editor2object(cleanup=True)
  7181. # ## EDITOR section
  7182. self.app.geo_editor = AppGeoEditor(self.app)
  7183. self.app.exc_editor = AppExcEditor(self.app)
  7184. self.app.grb_editor = AppGerberEditor(self.app)
  7185. # Clear pool
  7186. self.app.clear_pool()
  7187. for obj in self.app.collection.get_list():
  7188. # delete shapes left drawn from mark shape_collections, if any
  7189. if isinstance(obj, GerberObject):
  7190. try:
  7191. obj.mark_shapes_storage.clear()
  7192. obj.mark_shapes.clear(update=True)
  7193. obj.mark_shapes.enabled = False
  7194. except AttributeError:
  7195. pass
  7196. # also delete annotation shapes, if any
  7197. elif isinstance(obj, CNCJobObject):
  7198. try:
  7199. obj.text_col.enabled = False
  7200. del obj.text_col
  7201. obj.annotation.clear(update=True)
  7202. del obj.annotation
  7203. except AttributeError:
  7204. pass
  7205. # delete the exclusion areas
  7206. self.app.exc_areas.clear_shapes()
  7207. # tcl needs to be reinitialized, otherwise old shell variables etc remains
  7208. self.app.shell.init_tcl()
  7209. # delete any selection shape on canvas
  7210. self.app.delete_selection_shape()
  7211. # delete all FlatCAM objects
  7212. self.app.collection.delete_all()
  7213. # add in Selected tab an initial text that describe the flow of work in FlatCAm
  7214. self.app.setup_default_properties_tab()
  7215. # Clear project filename
  7216. self.app.project_filename = None
  7217. # Load the application defaults
  7218. self.defaults.load(filename=os.path.join(self.app.data_path, 'current_defaults.FlatConfig'), inform=self.inform)
  7219. # Re-fresh project options
  7220. self.app.on_options_app2project()
  7221. # Init FlatCAMTools
  7222. self.app.init_tools()
  7223. # Try to close all tabs in the PlotArea but only if the appGUI is active (CLI is None)
  7224. if cli is None:
  7225. # we need to go in reverse because once we remove a tab then the index changes
  7226. # meaning that removing the first tab (idx = 0) then the tab at former idx = 1 will assume idx = 0
  7227. # and so on. Therefore the deletion should be done in reverse
  7228. wdg_count = self.app.ui.plot_tab_area.tabBar.count() - 1
  7229. for index in range(wdg_count, -1, -1):
  7230. try:
  7231. self.app.ui.plot_tab_area.closeTab(index)
  7232. except Exception as e:
  7233. log.debug("App.on_file_new() --> %s" % str(e))
  7234. # # And then add again the Plot Area
  7235. self.app.ui.plot_tab_area.insertTab(0, self.app.ui.plot_tab, _("Plot Area"))
  7236. self.app.ui.plot_tab_area.protectTab(0)
  7237. # take the focus of the Notebook on Project Tab.
  7238. self.app.ui.notebook.setCurrentWidget(self.app.ui.project_tab)
  7239. self.app.set_ui_title(name=_("New Project - Not saved"))
  7240. def on_filenewscript(self, silent=False):
  7241. """
  7242. Will create a new script file and open it in the Code Editor
  7243. :param silent: if True will not display status messages
  7244. :return: None
  7245. """
  7246. if silent is False:
  7247. self.inform.emit('[success] %s' % _("New TCL script file created in Code Editor."))
  7248. # hide coordinates toolbars in the infobar while in DB
  7249. self.app.ui.coords_toolbar.hide()
  7250. self.app.ui.delta_coords_toolbar.hide()
  7251. self.app.app_obj.new_script_object()
  7252. def on_fileopenscript(self, name=None, silent=False):
  7253. """
  7254. Will open a Tcl script file into the Code Editor
  7255. :param silent: if True will not display status messages
  7256. :param name: name of a Tcl script file to open
  7257. :return: None
  7258. """
  7259. self.app.log.debug("on_fileopenscript()")
  7260. _filter_ = "TCL script .FlatScript (*.FlatScript);;TCL script .tcl (*.TCL);;TCL script .txt (*.TXT);;" \
  7261. "All Files (*.*)"
  7262. if name:
  7263. filenames = [name]
  7264. else:
  7265. try:
  7266. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(
  7267. caption=_("Open TCL script"), directory=self.app.get_last_folder(), filter=_filter_)
  7268. except TypeError:
  7269. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open TCL script"), filter=_filter_)
  7270. if len(filenames) == 0:
  7271. if silent is False:
  7272. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  7273. else:
  7274. for filename in filenames:
  7275. if filename != '':
  7276. self.worker_task.emit({'fcn': self.open_script, 'params': [filename]})
  7277. def on_fileopenscript_example(self, name=None, silent=False):
  7278. """
  7279. Will open a Tcl script file into the Code Editor
  7280. :param silent: if True will not display status messages
  7281. :param name: name of a Tcl script file to open
  7282. :return:
  7283. """
  7284. self.app.log.debug("on_fileopenscript_example()")
  7285. _filter_ = "TCL script .FlatScript (*.FlatScript);;TCL script .tcl (*.TCL);;TCL script .txt (*.TXT);;" \
  7286. "All Files (*.*)"
  7287. # test if the app was frozen and choose the path for the configuration file
  7288. if getattr(sys, "frozen", False) is True:
  7289. example_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\assets\\examples'
  7290. else:
  7291. example_path = os.path.dirname(os.path.realpath(__file__)) + '\\assets\\examples'
  7292. if name:
  7293. filenames = [name]
  7294. else:
  7295. try:
  7296. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(
  7297. caption=_("Open TCL script"), directory=example_path, filter=_filter_)
  7298. except TypeError:
  7299. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open TCL script"), filter=_filter_)
  7300. if len(filenames) == 0:
  7301. if silent is False:
  7302. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  7303. else:
  7304. for filename in filenames:
  7305. if filename != '':
  7306. self.worker_task.emit({'fcn': self.open_script, 'params': [filename]})
  7307. def on_filerunscript(self, name=None, silent=False):
  7308. """
  7309. File menu callback for loading and running a TCL script.
  7310. :param silent: if True will not display status messages
  7311. :param name: name of a Tcl script file to be run by FlatCAM
  7312. :return: None
  7313. """
  7314. self.app.log.debug("on_file_runscript()")
  7315. if name:
  7316. filename = name
  7317. if self.app.cmd_line_headless != 1:
  7318. self.splash.showMessage('%s: %ssec\n%s' %
  7319. (_("Canvas initialization started.\n"
  7320. "Canvas initialization finished in"), '%.2f' % self.app.used_time,
  7321. _("Executing ScriptObject file.")
  7322. ),
  7323. alignment=Qt.AlignBottom | Qt.AlignLeft,
  7324. color=QtGui.QColor("gray"))
  7325. else:
  7326. _filter_ = "TCL script .FlatScript (*.FlatScript);;TCL script .tcl (*.TCL);;TCL script .txt (*.TXT);;" \
  7327. "All Files (*.*)"
  7328. try:
  7329. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Run TCL script"),
  7330. directory=self.app.get_last_folder(),
  7331. filter=_filter_)
  7332. except TypeError:
  7333. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Run TCL script"), filter=_filter_)
  7334. # The Qt methods above will return a QString which can cause problems later.
  7335. # So far json.dump() will fail to serialize it.
  7336. filename = str(filename)
  7337. if filename == "":
  7338. if silent is False:
  7339. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  7340. else:
  7341. if self.app.cmd_line_headless != 1:
  7342. if self.app.ui.shell_dock.isHidden():
  7343. self.app.ui.shell_dock.show()
  7344. try:
  7345. with open(filename, "r") as tcl_script:
  7346. cmd_line_shellfile_content = tcl_script.read()
  7347. if self.app.cmd_line_headless != 1:
  7348. self.app.shell.exec_command(cmd_line_shellfile_content)
  7349. else:
  7350. self.app.shell.exec_command(cmd_line_shellfile_content, no_echo=True)
  7351. if silent is False:
  7352. self.inform.emit('[success] %s' % _("TCL script file opened in Code Editor and executed."))
  7353. except Exception as e:
  7354. self.app.debug("App.on_filerunscript() -> %s" % str(e))
  7355. sys.exit(2)
  7356. def on_file_saveproject(self, silent=False):
  7357. """
  7358. Callback for menu item File->Save Project. Saves the project to
  7359. ``self.project_filename`` or calls ``self.on_file_saveprojectas()``
  7360. if set to None. The project is saved by calling ``self.save_project()``.
  7361. :param silent: if True will not display status messages
  7362. :return: None
  7363. """
  7364. if self.app.project_filename is None:
  7365. self.on_file_saveprojectas()
  7366. else:
  7367. self.worker_task.emit({'fcn': self.save_project, 'params': [self.app.project_filename, silent]})
  7368. if self.defaults["global_open_style"] is False:
  7369. self.app.file_opened.emit("project", self.project_filename)
  7370. self.app.file_saved.emit("project", self.project_filename)
  7371. self.app.set_ui_title(name=self.app.project_filename)
  7372. self.app.should_we_save = False
  7373. def on_file_saveprojectas(self, make_copy=False, use_thread=True, quit_action=False):
  7374. """
  7375. Callback for menu item File->Save Project As... Opens a file
  7376. chooser and saves the project to the given file via
  7377. ``self.save_project()``.
  7378. :param make_copy if to be create a copy of the project; boolean
  7379. :param use_thread: if to be run in a separate thread; boolean
  7380. :param quit_action: if to be followed by quiting the application; boolean
  7381. :return: None
  7382. """
  7383. date = str(datetime.today()).rpartition('.')[0]
  7384. date = ''.join(c for c in date if c not in ':-')
  7385. date = self.date.replace(' ', '_')
  7386. filter_ = "FlatCAM Project .FlatPrj (*.FlatPrj);; All Files (*.*)"
  7387. try:
  7388. filename, _f = FCFileSaveDialog.get_saved_filename(
  7389. caption=_("Save Project As ..."),
  7390. directory='{l_save}/{proj}_{date}'.format(l_save=str(self.app.get_last_save_folder()), date=date,
  7391. proj=_("Project")),
  7392. ext_filter=filter_
  7393. )
  7394. except TypeError:
  7395. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Project As ..."), ext_filter=filter_)
  7396. filename = str(filename)
  7397. if filename == '':
  7398. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  7399. return
  7400. if use_thread is True:
  7401. self.worker_task.emit({'fcn': self.save_project, 'params': [filename, quit_action]})
  7402. else:
  7403. self.save_project(filename, quit_action)
  7404. # self.save_project(filename)
  7405. if self.defaults["global_open_style"] is False:
  7406. self.app.file_opened.emit("project", filename)
  7407. self.app.file_saved.emit("project", filename)
  7408. if not make_copy:
  7409. self.app.project_filename = filename
  7410. self.app.set_ui_title(name=self.app.project_filename)
  7411. self.app.should_we_save = False
  7412. def on_file_save_objects_pdf(self, use_thread=True):
  7413. date = str(datetime.today()).rpartition('.')[0]
  7414. date = ''.join(c for c in date if c not in ':-')
  7415. date = date.replace(' ', '_')
  7416. try:
  7417. obj_selection = self.app.collection.get_selected()
  7418. if len(obj_selection) == 1:
  7419. obj_name = str(obj_selection[0].options['name'])
  7420. else:
  7421. obj_name = _("FlatCAM objects print")
  7422. except AttributeError as err:
  7423. self.app.log.debug("App.on_file_save_object_pdf() --> %s" % str(err))
  7424. self.inform.emit('[ERROR_NOTCL] %s' % _("No object selected."))
  7425. return
  7426. if not obj_selection:
  7427. self.inform.emit('[ERROR_NOTCL] %s' % _("No object selected."))
  7428. return
  7429. filter_ = "PDF File .pdf (*.PDF);; All Files (*.*)"
  7430. try:
  7431. filename, _f = FCFileSaveDialog.get_saved_filename(
  7432. caption=_("Save Object as PDF ..."),
  7433. directory='{l_save}/{obj_name}_{date}'.format(l_save=str(self.app.get_last_save_folder()),
  7434. obj_name=obj_name,
  7435. date=date),
  7436. ext_filter=filter_
  7437. )
  7438. except TypeError:
  7439. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Object as PDF ..."), ext_filter=filter_)
  7440. filename = str(filename)
  7441. if filename == '':
  7442. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  7443. return
  7444. if use_thread is True:
  7445. self.app.proc_container.new(_("Printing PDF ... Please wait."))
  7446. self.worker_task.emit({'fcn': self.save_pdf, 'params': [filename, obj_selection]})
  7447. else:
  7448. self.save_pdf(filename, obj_selection)
  7449. # self.save_project(filename)
  7450. if self.defaults["global_open_style"] is False:
  7451. self.app.file_opened.emit("pdf", filename)
  7452. self.app.file_saved.emit("pdf", filename)
  7453. def save_pdf(self, file_name, obj_selection):
  7454. p_size = self.defaults['global_workspaceT']
  7455. orientation = self.defaults['global_workspace_orientation']
  7456. color = 'black'
  7457. transparency_level = 1.0
  7458. self.app.pagesize = {}
  7459. self.app.pagesize.update(
  7460. {
  7461. 'Bounds': None,
  7462. 'A0': (841 * mm, 1189 * mm),
  7463. 'A1': (594 * mm, 841 * mm),
  7464. 'A2': (420 * mm, 594 * mm),
  7465. 'A3': (297 * mm, 420 * mm),
  7466. 'A4': (210 * mm, 297 * mm),
  7467. 'A5': (148 * mm, 210 * mm),
  7468. 'A6': (105 * mm, 148 * mm),
  7469. 'A7': (74 * mm, 105 * mm),
  7470. 'A8': (52 * mm, 74 * mm),
  7471. 'A9': (37 * mm, 52 * mm),
  7472. 'A10': (26 * mm, 37 * mm),
  7473. 'B0': (1000 * mm, 1414 * mm),
  7474. 'B1': (707 * mm, 1000 * mm),
  7475. 'B2': (500 * mm, 707 * mm),
  7476. 'B3': (353 * mm, 500 * mm),
  7477. 'B4': (250 * mm, 353 * mm),
  7478. 'B5': (176 * mm, 250 * mm),
  7479. 'B6': (125 * mm, 176 * mm),
  7480. 'B7': (88 * mm, 125 * mm),
  7481. 'B8': (62 * mm, 88 * mm),
  7482. 'B9': (44 * mm, 62 * mm),
  7483. 'B10': (31 * mm, 44 * mm),
  7484. 'C0': (917 * mm, 1297 * mm),
  7485. 'C1': (648 * mm, 917 * mm),
  7486. 'C2': (458 * mm, 648 * mm),
  7487. 'C3': (324 * mm, 458 * mm),
  7488. 'C4': (229 * mm, 324 * mm),
  7489. 'C5': (162 * mm, 229 * mm),
  7490. 'C6': (114 * mm, 162 * mm),
  7491. 'C7': (81 * mm, 114 * mm),
  7492. 'C8': (57 * mm, 81 * mm),
  7493. 'C9': (40 * mm, 57 * mm),
  7494. 'C10': (28 * mm, 40 * mm),
  7495. # American paper sizes
  7496. 'LETTER': (8.5 * inch, 11 * inch),
  7497. 'LEGAL': (8.5 * inch, 14 * inch),
  7498. 'ELEVENSEVENTEEN': (11 * inch, 17 * inch),
  7499. # From https://en.wikipedia.org/wiki/Paper_size
  7500. 'JUNIOR_LEGAL': (5 * inch, 8 * inch),
  7501. 'HALF_LETTER': (5.5 * inch, 8 * inch),
  7502. 'GOV_LETTER': (8 * inch, 10.5 * inch),
  7503. 'GOV_LEGAL': (8.5 * inch, 13 * inch),
  7504. 'LEDGER': (17 * inch, 11 * inch),
  7505. }
  7506. )
  7507. exported_svg = []
  7508. for obj in obj_selection:
  7509. svg_obj = obj.export_svg(scale_stroke_factor=0.0, scale_factor_x=None, scale_factor_y=None,
  7510. skew_factor_x=None, skew_factor_y=None, mirror=None)
  7511. if obj.kind.lower() == 'gerber':
  7512. # color = self.defaults["gerber_plot_fill"][:-2]
  7513. color = obj.fill_color[:-2]
  7514. elif obj.kind.lower() == 'excellon':
  7515. color = '#C40000'
  7516. elif obj.kind.lower() == 'geometry':
  7517. color = self.defaults["global_draw_color"]
  7518. # Change the attributes of the exported SVG
  7519. # We don't need stroke-width
  7520. # We set opacity to maximum
  7521. # We set the colour to WHITE
  7522. root = ET.fromstring(svg_obj)
  7523. for child in root:
  7524. child.set('fill', str(color))
  7525. child.set('opacity', str(transparency_level))
  7526. child.set('stroke', str(color))
  7527. exported_svg.append(ET.tostring(root))
  7528. xmin = Inf
  7529. ymin = Inf
  7530. xmax = -Inf
  7531. ymax = -Inf
  7532. for obj in obj_selection:
  7533. try:
  7534. gxmin, gymin, gxmax, gymax = obj.bounds()
  7535. xmin = min([xmin, gxmin])
  7536. ymin = min([ymin, gymin])
  7537. xmax = max([xmax, gxmax])
  7538. ymax = max([ymax, gymax])
  7539. except Exception as e:
  7540. self.app.log.warning(
  7541. "DEV WARNING: Tried to get bounds of empty geometry in App.save_pdf(). %s" % str(e))
  7542. # Determine bounding area for svg export
  7543. bounds = [xmin, ymin, xmax, ymax]
  7544. size = bounds[2] - bounds[0], bounds[3] - bounds[1]
  7545. # This contain the measure units
  7546. uom = obj_selection[0].units.lower()
  7547. # Define a boundary around SVG of about 1.0mm (~39mils)
  7548. if uom in "mm":
  7549. boundary = 1.0
  7550. else:
  7551. boundary = 0.0393701
  7552. # Convert everything to strings for use in the xml doc
  7553. svgwidth = str(size[0] + (2 * boundary))
  7554. svgheight = str(size[1] + (2 * boundary))
  7555. minx = str(bounds[0] - boundary)
  7556. miny = str(bounds[1] + boundary + size[1])
  7557. # Add a SVG Header and footer to the svg output from shapely
  7558. # The transform flips the Y Axis so that everything renders
  7559. # properly within svg apps such as inkscape
  7560. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  7561. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  7562. svg_header += 'width="' + svgwidth + uom + '" '
  7563. svg_header += 'height="' + svgheight + uom + '" '
  7564. svg_header += 'viewBox="' + minx + ' -' + miny + ' ' + svgwidth + ' ' + svgheight + '" '
  7565. svg_header += '>'
  7566. svg_header += '<g transform="scale(1,-1)">'
  7567. svg_footer = '</g> </svg>'
  7568. svg_elem = str(svg_header)
  7569. for svg_item in exported_svg:
  7570. svg_elem += str(svg_item)
  7571. svg_elem += str(svg_footer)
  7572. # Parse the xml through a xml parser just to add line feeds
  7573. # and to make it look more pretty for the output
  7574. doc = parse_xml_string(svg_elem)
  7575. doc_final = doc.toprettyxml()
  7576. try:
  7577. if self.defaults['units'].upper() == 'IN':
  7578. unit = inch
  7579. else:
  7580. unit = mm
  7581. doc_final = StringIO(doc_final)
  7582. drawing = svg2rlg(doc_final)
  7583. if p_size == 'Bounds':
  7584. renderPDF.drawToFile(drawing, file_name)
  7585. else:
  7586. if orientation == 'p':
  7587. page_size = portrait(self.pagesize[p_size])
  7588. else:
  7589. page_size = landscape(self.pagesize[p_size])
  7590. my_canvas = canvas.Canvas(file_name, pagesize=page_size)
  7591. my_canvas.translate(bounds[0] * unit, bounds[1] * unit)
  7592. renderPDF.draw(drawing, my_canvas, 0, 0)
  7593. my_canvas.save()
  7594. except Exception as e:
  7595. self.app.log.debug("MenuFileHandlers.save_pdf() --> PDF output --> %s" % str(e))
  7596. return 'fail'
  7597. self.inform.emit('[success] %s: %s' % (_("PDF file saved to"), file_name))
  7598. def export_svg(self, obj_name, filename, scale_stroke_factor=0.00):
  7599. """
  7600. Exports a Geometry Object to an SVG file.
  7601. :param obj_name: the name of the FlatCAM object to be saved as SVG
  7602. :param filename: Path to the SVG file to save to.
  7603. :param scale_stroke_factor: factor by which to change/scale the thickness of the features
  7604. :return:
  7605. """
  7606. if filename is None:
  7607. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  7608. is not None else self.defaults["global_last_folder"]
  7609. self.app.log.debug("export_svg()")
  7610. try:
  7611. obj = self.app.collection.get_by_name(str(obj_name))
  7612. except Exception:
  7613. return 'fail'
  7614. with self.app.proc_container.new(_("Exporting SVG")) as proc:
  7615. exported_svg = obj.export_svg(scale_stroke_factor=scale_stroke_factor)
  7616. # Determine bounding area for svg export
  7617. bounds = obj.bounds()
  7618. size = obj.size()
  7619. # Convert everything to strings for use in the xml doc
  7620. svgwidth = str(size[0])
  7621. svgheight = str(size[1])
  7622. minx = str(bounds[0])
  7623. miny = str(bounds[1] - size[1])
  7624. uom = obj.units.lower()
  7625. # Add a SVG Header and footer to the svg output from shapely
  7626. # The transform flips the Y Axis so that everything renders
  7627. # properly within svg apps such as inkscape
  7628. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  7629. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  7630. svg_header += 'width="' + svgwidth + uom + '" '
  7631. svg_header += 'height="' + svgheight + uom + '" '
  7632. svg_header += 'viewBox="' + minx + ' ' + miny + ' ' + svgwidth + ' ' + svgheight + '">'
  7633. svg_header += '<g transform="scale(1,-1)">'
  7634. svg_footer = '</g> </svg>'
  7635. svg_elem = svg_header + exported_svg + svg_footer
  7636. # Parse the xml through a xml parser just to add line feeds
  7637. # and to make it look more pretty for the output
  7638. svgcode = parse_xml_string(svg_elem)
  7639. svgcode = svgcode.toprettyxml()
  7640. try:
  7641. with open(filename, 'w') as fp:
  7642. fp.write(svgcode)
  7643. except PermissionError:
  7644. self.inform.emit('[WARNING] %s' %
  7645. _("Permission denied, saving not possible.\n"
  7646. "Most likely another app is holding the file open and not accessible."))
  7647. return 'fail'
  7648. if self.defaults["global_open_style"] is False:
  7649. self.app.file_opened.emit("SVG", filename)
  7650. self.app.file_saved.emit("SVG", filename)
  7651. self.inform.emit('[success] %s: %s' % (_("SVG file exported to"), filename))
  7652. def on_import_preferences(self):
  7653. """
  7654. Loads the application default settings from a saved file into
  7655. ``self.defaults`` dictionary.
  7656. :return: None
  7657. """
  7658. self.app.log.debug("App.on_import_preferences()")
  7659. # Show file chooser
  7660. filter_ = "Config File (*.FlatConfig);;All Files (*.*)"
  7661. try:
  7662. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import FlatCAM Preferences"),
  7663. directory=self.app.data_path,
  7664. filter=filter_)
  7665. except TypeError:
  7666. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import FlatCAM Preferences"),
  7667. filter=filter_)
  7668. filename = str(filename)
  7669. if filename == "":
  7670. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  7671. return
  7672. # Load in the defaults from the chosen file
  7673. self.defaults.load(filename=filename, inform=self.inform)
  7674. self.app.preferencesUiManager.on_preferences_edited()
  7675. self.inform.emit('[success] %s: %s' % (_("Imported Defaults from"), filename))
  7676. def on_export_preferences(self):
  7677. """
  7678. Save the defaults dictionary to a file.
  7679. :return: None
  7680. """
  7681. self.app.log.debug("on_export_preferences()")
  7682. # defaults_file_content = None
  7683. # Show file chooser
  7684. date = str(datetime.today()).rpartition('.')[0]
  7685. date = ''.join(c for c in date if c not in ':-')
  7686. date = date.replace(' ', '_')
  7687. filter__ = "Config File .FlatConfig (*.FlatConfig);;All Files (*.*)"
  7688. try:
  7689. filename, _f = FCFileSaveDialog.get_saved_filename(
  7690. caption=_("Export FlatCAM Preferences"),
  7691. directory=self.app.data_path + '/preferences_' + date,
  7692. ext_filter=filter__
  7693. )
  7694. except TypeError:
  7695. filename, _f = FCFileSaveDialog.get_saved_filename(
  7696. caption=_("Export FlatCAM Preferences"), ext_filter=filter__)
  7697. filename = str(filename)
  7698. if filename == "":
  7699. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  7700. return 'fail'
  7701. # Update options
  7702. self.app.preferencesUiManager.defaults_read_form()
  7703. self.defaults.propagate_defaults()
  7704. # Save update options
  7705. try:
  7706. self.defaults.write(filename=filename)
  7707. except Exception:
  7708. self.inform.emit('[ERROR_NOTCL] %s %s' % (_("Failed to write defaults to file."), str(filename)))
  7709. return
  7710. if self.defaults["global_open_style"] is False:
  7711. self.app.file_opened.emit("preferences", filename)
  7712. self.app.file_saved.emit("preferences", filename)
  7713. self.inform.emit('[success] %s: %s' % (_("Exported preferences to"), filename))
  7714. def export_excellon(self, obj_name, filename, local_use=None, use_thread=True):
  7715. """
  7716. Exports a Excellon Object to an Excellon file.
  7717. :param obj_name: the name of the FlatCAM object to be saved as Excellon
  7718. :param filename: Path to the Excellon file to save to.
  7719. :param local_use:
  7720. :param use_thread: if to be run in a separate thread
  7721. :return:
  7722. """
  7723. if filename is None:
  7724. if self.defaults["global_last_save_folder"]:
  7725. filename = self.defaults["global_last_save_folder"] + '/' + 'exported_excellon'
  7726. else:
  7727. filename = self.defaults["global_last_folder"] + '/' + 'exported_excellon'
  7728. self.app.log.debug("export_excellon()")
  7729. format_exc = ';FILE_FORMAT=%d:%d\n' % (self.defaults["excellon_exp_integer"],
  7730. self.defaults["excellon_exp_decimals"]
  7731. )
  7732. if local_use is None:
  7733. try:
  7734. obj = self.app.collection.get_by_name(str(obj_name))
  7735. except Exception:
  7736. return "Could not retrieve object: %s" % obj_name
  7737. else:
  7738. obj = local_use
  7739. if not isinstance(obj, ExcellonObject):
  7740. self.inform.emit('[ERROR_NOTCL] %s' %
  7741. _("Failed. Only Excellon objects can be saved as Excellon files..."))
  7742. return
  7743. # updated units
  7744. eunits = self.defaults["excellon_exp_units"]
  7745. ewhole = self.defaults["excellon_exp_integer"]
  7746. efract = self.defaults["excellon_exp_decimals"]
  7747. ezeros = self.defaults["excellon_exp_zeros"]
  7748. eformat = self.defaults["excellon_exp_format"]
  7749. slot_type = self.defaults["excellon_exp_slot_type"]
  7750. fc_units = self.defaults['units'].upper()
  7751. if fc_units == 'MM':
  7752. factor = 1 if eunits == 'METRIC' else 0.03937
  7753. else:
  7754. factor = 25.4 if eunits == 'METRIC' else 1
  7755. def make_excellon():
  7756. try:
  7757. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  7758. header = 'M48\n'
  7759. header += ';EXCELLON GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s\n' % \
  7760. (str(self.app.version), str(self.app.version_date))
  7761. header += ';Filename: %s' % str(obj_name) + '\n'
  7762. header += ';Created on : %s' % time_str + '\n'
  7763. if eformat == 'dec':
  7764. has_slots, excellon_code = obj.export_excellon(ewhole, efract, factor=factor, slot_type=slot_type)
  7765. header += eunits + '\n'
  7766. for tool in obj.tools:
  7767. if eunits == 'METRIC':
  7768. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['tooldia']) * factor,
  7769. tool=str(tool),
  7770. dec=2)
  7771. else:
  7772. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['tooldia']) * factor,
  7773. tool=str(tool),
  7774. dec=4)
  7775. else:
  7776. if ezeros == 'LZ':
  7777. has_slots, excellon_code = obj.export_excellon(ewhole, efract,
  7778. form='ndec', e_zeros='LZ', factor=factor,
  7779. slot_type=slot_type)
  7780. header += '%s,%s\n' % (eunits, 'LZ')
  7781. header += format_exc
  7782. for tool in obj.tools:
  7783. if eunits == 'METRIC':
  7784. header += "T{tool}F00S00C{:.{dec}f}\n".format(
  7785. float(obj.tools[tool]['tooldia']) * factor,
  7786. tool=str(tool),
  7787. dec=2)
  7788. else:
  7789. header += "T{tool}F00S00C{:.{dec}f}\n".format(
  7790. float(obj.tools[tool]['tooldia']) * factor,
  7791. tool=str(tool),
  7792. dec=4)
  7793. else:
  7794. has_slots, excellon_code = obj.export_excellon(ewhole, efract,
  7795. form='ndec', e_zeros='TZ', factor=factor,
  7796. slot_type=slot_type)
  7797. header += '%s,%s\n' % (eunits, 'TZ')
  7798. header += format_exc
  7799. for tool in obj.tools:
  7800. if eunits == 'METRIC':
  7801. header += "T{tool}F00S00C{:.{dec}f}\n".format(
  7802. float(obj.tools[tool]['tooldia']) * factor,
  7803. tool=str(tool),
  7804. dec=2)
  7805. else:
  7806. header += "T{tool}F00S00C{:.{dec}f}\n".format(
  7807. float(obj.tools[tool]['tooldia']) * factor,
  7808. tool=str(tool),
  7809. dec=4)
  7810. header += '%\n'
  7811. footer = 'M30\n'
  7812. exported_excellon = header
  7813. exported_excellon += excellon_code
  7814. exported_excellon += footer
  7815. if local_use is None:
  7816. try:
  7817. with open(filename, 'w') as fp:
  7818. fp.write(exported_excellon)
  7819. except PermissionError:
  7820. self.inform.emit('[WARNING] %s' %
  7821. _("Permission denied, saving not possible.\n"
  7822. "Most likely another app is holding the file open and not accessible."))
  7823. return 'fail'
  7824. if self.defaults["global_open_style"] is False:
  7825. self.app.file_opened.emit("Excellon", filename)
  7826. self.app.file_saved.emit("Excellon", filename)
  7827. self.inform.emit('[success] %s: %s' % (_("Excellon file exported to"), filename))
  7828. else:
  7829. return exported_excellon
  7830. except Exception as e:
  7831. self.app.log.debug("App.export_excellon.make_excellon() --> %s" % str(e))
  7832. return 'fail'
  7833. if use_thread is True:
  7834. with self.app.proc_container.new(_("Exporting Excellon")) as proc:
  7835. def job_thread_exc(app_obj):
  7836. ret = make_excellon()
  7837. if ret == 'fail':
  7838. self.inform.emit('[ERROR_NOTCL] %s' % _('Could not export Excellon file.'))
  7839. return
  7840. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  7841. else:
  7842. eret = make_excellon()
  7843. if eret == 'fail':
  7844. self.inform.emit('[ERROR_NOTCL] %s' % _('Could not export Excellon file.'))
  7845. return 'fail'
  7846. if local_use is not None:
  7847. return eret
  7848. def export_gerber(self, obj_name, filename, local_use=None, use_thread=True):
  7849. """
  7850. Exports a Gerber Object to an Gerber file.
  7851. :param obj_name: the name of the FlatCAM object to be saved as Gerber
  7852. :param filename: Path to the Gerber file to save to.
  7853. :param local_use: if the Gerber code is to be saved to a file (None) or used within FlatCAM.
  7854. When not None, the value will be the actual Gerber object for which to create
  7855. the Gerber code
  7856. :param use_thread: if to be run in a separate thread
  7857. :return:
  7858. """
  7859. if filename is None:
  7860. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  7861. is not None else self.defaults["global_last_folder"]
  7862. self.app.log.debug("export_gerber()")
  7863. if local_use is None:
  7864. try:
  7865. obj = self.app.collection.get_by_name(str(obj_name))
  7866. except Exception:
  7867. return 'fail'
  7868. else:
  7869. obj = local_use
  7870. # updated units
  7871. gunits = self.defaults["gerber_exp_units"]
  7872. gwhole = self.defaults["gerber_exp_integer"]
  7873. gfract = self.defaults["gerber_exp_decimals"]
  7874. gzeros = self.defaults["gerber_exp_zeros"]
  7875. fc_units = self.defaults['units'].upper()
  7876. if fc_units == 'MM':
  7877. factor = 1 if gunits == 'MM' else 0.03937
  7878. else:
  7879. factor = 25.4 if gunits == 'MM' else 1
  7880. def make_gerber():
  7881. try:
  7882. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  7883. header = 'G04*\n'
  7884. header += 'G04 RS-274X GERBER GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s*\n' % \
  7885. (str(self.app.version), str(self.app.version_date))
  7886. header += 'G04 Filename: %s*' % str(obj_name) + '\n'
  7887. header += 'G04 Created on : %s*' % time_str + '\n'
  7888. header += '%%FS%sAX%s%sY%s%s*%%\n' % (gzeros, gwhole, gfract, gwhole, gfract)
  7889. header += "%MO{units}*%\n".format(units=gunits)
  7890. for apid in obj.apertures:
  7891. if obj.apertures[apid]['type'] == 'C':
  7892. header += "%ADD{apid}{type},{size}*%\n".format(
  7893. apid=str(apid),
  7894. type='C',
  7895. size=(factor * obj.apertures[apid]['size'])
  7896. )
  7897. elif obj.apertures[apid]['type'] == 'R':
  7898. header += "%ADD{apid}{type},{width}X{height}*%\n".format(
  7899. apid=str(apid),
  7900. type='R',
  7901. width=(factor * obj.apertures[apid]['width']),
  7902. height=(factor * obj.apertures[apid]['height'])
  7903. )
  7904. elif obj.apertures[apid]['type'] == 'O':
  7905. header += "%ADD{apid}{type},{width}X{height}*%\n".format(
  7906. apid=str(apid),
  7907. type='O',
  7908. width=(factor * obj.apertures[apid]['width']),
  7909. height=(factor * obj.apertures[apid]['height'])
  7910. )
  7911. header += '\n'
  7912. # obsolete units but some software may need it
  7913. if gunits == 'IN':
  7914. header += 'G70*\n'
  7915. else:
  7916. header += 'G71*\n'
  7917. # Absolute Mode
  7918. header += 'G90*\n'
  7919. header += 'G01*\n'
  7920. # positive polarity
  7921. header += '%LPD*%\n'
  7922. footer = 'M02*\n'
  7923. gerber_code = obj.export_gerber(gwhole, gfract, g_zeros=gzeros, factor=factor)
  7924. exported_gerber = header
  7925. exported_gerber += gerber_code
  7926. exported_gerber += footer
  7927. if local_use is None:
  7928. try:
  7929. with open(filename, 'w') as fp:
  7930. fp.write(exported_gerber)
  7931. except PermissionError:
  7932. self.inform.emit('[WARNING] %s' %
  7933. _("Permission denied, saving not possible.\n"
  7934. "Most likely another app is holding the file open and not accessible."))
  7935. return 'fail'
  7936. if self.defaults["global_open_style"] is False:
  7937. self.app.file_opened.emit("Gerber", filename)
  7938. self.app.file_saved.emit("Gerber", filename)
  7939. self.inform.emit('[success] %s: %s' % (_("Gerber file exported to"), filename))
  7940. else:
  7941. return exported_gerber
  7942. except Exception as e:
  7943. log.debug("App.export_gerber.make_gerber() --> %s" % str(e))
  7944. return 'fail'
  7945. if use_thread is True:
  7946. with self.app.proc_container.new(_("Exporting Gerber")) as proc:
  7947. def job_thread_grb(app_obj):
  7948. ret = make_gerber()
  7949. if ret == 'fail':
  7950. self.inform.emit('[ERROR_NOTCL] %s' % _('Could not export file.'))
  7951. return
  7952. self.worker_task.emit({'fcn': job_thread_grb, 'params': [self]})
  7953. else:
  7954. gret = make_gerber()
  7955. if gret == 'fail':
  7956. self.inform.emit('[ERROR_NOTCL] %s' % _('Could not export file.'))
  7957. return 'fail'
  7958. if local_use is not None:
  7959. return gret
  7960. def export_dxf(self, obj_name, filename, local_use=None, use_thread=True):
  7961. """
  7962. Exports a Geometry Object to an DXF file.
  7963. :param obj_name: the name of the FlatCAM object to be saved as DXF
  7964. :param filename: Path to the DXF file to save to.
  7965. :param local_use: if the Gerber code is to be saved to a file (None) or used within FlatCAM.
  7966. When not None, the value will be the actual Geometry object for which to create
  7967. the Geometry/DXF code
  7968. :param use_thread: if to be run in a separate thread
  7969. :return:
  7970. """
  7971. if filename is None:
  7972. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  7973. is not None else self.defaults["global_last_folder"]
  7974. self.app.log.debug("export_dxf()")
  7975. if local_use is None:
  7976. try:
  7977. obj = self.app.collection.get_by_name(str(obj_name))
  7978. except Exception:
  7979. return 'fail'
  7980. else:
  7981. obj = local_use
  7982. def make_dxf():
  7983. try:
  7984. dxf_code = obj.export_dxf()
  7985. if local_use is None:
  7986. try:
  7987. dxf_code.saveas(filename)
  7988. except PermissionError:
  7989. self.inform.emit('[WARNING] %s' %
  7990. _("Permission denied, saving not possible.\n"
  7991. "Most likely another app is holding the file open and not accessible."))
  7992. return 'fail'
  7993. if self.defaults["global_open_style"] is False:
  7994. self.app.file_opened.emit("DXF", filename)
  7995. self.app.file_saved.emit("DXF", filename)
  7996. self.inform.emit('[success] %s: %s' % (_("DXF file exported to"), filename))
  7997. else:
  7998. return dxf_code
  7999. except Exception as e:
  8000. log.debug("App.export_dxf.make_dxf() --> %s" % str(e))
  8001. return 'fail'
  8002. if use_thread is True:
  8003. with self.app.proc_container.new(_("Exporting DXF")) as proc:
  8004. def job_thread_exc(app_obj):
  8005. ret_dxf_val = make_dxf()
  8006. if ret_dxf_val == 'fail':
  8007. app_obj.inform.emit('[WARNING_NOTCL] %s' % _('Could not export DXF file.'))
  8008. return
  8009. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  8010. else:
  8011. ret = make_dxf()
  8012. if ret == 'fail':
  8013. self.inform.emit('[WARNING_NOTCL] %s' % _('Could not export DXF file.'))
  8014. return
  8015. if local_use is not None:
  8016. return ret
  8017. def import_svg(self, filename, geo_type='geometry', outname=None, plot=True):
  8018. """
  8019. Adds a new Geometry Object to the projects and populates
  8020. it with shapes extracted from the SVG file.
  8021. :param plot: If True then the resulting object will be plotted on canvas
  8022. :param filename: Path to the SVG file.
  8023. :param geo_type: Type of FlatCAM object that will be created from SVG
  8024. :param outname: The name given to the resulting FlatCAM object
  8025. :return:
  8026. """
  8027. self.app.log.debug("App.import_svg()")
  8028. obj_type = ""
  8029. if geo_type is None or geo_type == "geometry":
  8030. obj_type = "geometry"
  8031. elif geo_type == "gerber":
  8032. obj_type = "gerber"
  8033. else:
  8034. self.inform.emit('[ERROR_NOTCL] %s' %
  8035. _("Not supported type is picked as parameter. Only Geometry and Gerber are supported"))
  8036. return
  8037. units = self.defaults['units'].upper()
  8038. def obj_init(geo_obj, app_obj):
  8039. geo_obj.import_svg(filename, obj_type, units=units)
  8040. geo_obj.multigeo = True
  8041. with open(filename) as f:
  8042. file_content = f.read()
  8043. geo_obj.source_file = file_content
  8044. with self.app.proc_container.new(_("Importing SVG")) as proc:
  8045. # Object name
  8046. name = outname or filename.split('/')[-1].split('\\')[-1]
  8047. ret = self.app.app_obj.new_object(obj_type, name, obj_init, autoselected=False, plot=plot)
  8048. if ret == 'fail':
  8049. self.inform.emit('[ERROR_NOTCL]%s' % _('Import failed.'))
  8050. return 'fail'
  8051. # Register recent file
  8052. self.app.file_opened.emit("svg", filename)
  8053. # appGUI feedback
  8054. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  8055. def import_dxf(self, filename, geo_type='geometry', outname=None, plot=True):
  8056. """
  8057. Adds a new Geometry Object to the projects and populates
  8058. it with shapes extracted from the DXF file.
  8059. :param filename: Path to the DXF file.
  8060. :param geo_type: Type of FlatCAM object that will be created from DXF
  8061. :param outname: Name for the imported Geometry
  8062. :param plot: If True then the resulting object will be plotted on canvas
  8063. :return:
  8064. """
  8065. self.app.log.debug(" ********* Importing DXF as: %s ********* " % geo_type.capitalize())
  8066. obj_type = ""
  8067. if geo_type is None or geo_type == "geometry":
  8068. obj_type = "geometry"
  8069. elif geo_type == "gerber":
  8070. obj_type = geo_type
  8071. else:
  8072. self.inform.emit('[ERROR_NOTCL] %s' %
  8073. _("Not supported type is picked as parameter. Only Geometry and Gerber are supported"))
  8074. return
  8075. units = self.defaults['units'].upper()
  8076. def obj_init(geo_obj, app_obj):
  8077. if obj_type == "geometry":
  8078. geo_obj.import_dxf_as_geo(filename, units=units)
  8079. elif obj_type == "gerber":
  8080. geo_obj.import_dxf_as_gerber(filename, units=units)
  8081. else:
  8082. return "fail"
  8083. geo_obj.multigeo = True
  8084. with open(filename) as f:
  8085. file_content = f.read()
  8086. geo_obj.source_file = file_content
  8087. with self.app.proc_container.new(_("Importing DXF")):
  8088. # Object name
  8089. name = outname or filename.split('/')[-1].split('\\')[-1]
  8090. ret = self.app.app_obj.new_object(obj_type, name, obj_init, autoselected=False, plot=plot)
  8091. if ret == 'fail':
  8092. self.inform.emit('[ERROR_NOTCL]%s' % _('Import failed.'))
  8093. return 'fail'
  8094. # Register recent file
  8095. self.app.file_opened.emit("dxf", filename)
  8096. # appGUI feedback
  8097. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  8098. def open_gerber(self, filename, outname=None, plot=True, from_tcl=False):
  8099. """
  8100. Opens a Gerber file, parses it and creates a new object for
  8101. it in the program. Thread-safe.
  8102. :param outname: Name of the resulting object. None causes the
  8103. name to be that of the file. Str.
  8104. :param filename: Gerber file filename
  8105. :type filename: str
  8106. :param plot: boolean, to plot or not the resulting object
  8107. :param from_tcl: True if run from Tcl Shell
  8108. :return: None
  8109. """
  8110. # How the object should be initialized
  8111. def obj_init(gerber_obj, app_obj):
  8112. assert isinstance(gerber_obj, GerberObject), \
  8113. "Expected to initialize a GerberObject but got %s" % type(gerber_obj)
  8114. # Opening the file happens here
  8115. try:
  8116. gerber_obj.parse_file(filename)
  8117. except IOError:
  8118. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open file"), filename))
  8119. return "fail"
  8120. except ParseError as err:
  8121. app_obj.inform.emit('[ERROR_NOTCL] %s: %s. %s' % (_("Failed to parse file"), filename, str(err)))
  8122. app_obj.log.error(str(err))
  8123. return "fail"
  8124. except Exception as e:
  8125. log.debug("App.open_gerber() --> %s" % str(e))
  8126. msg = '[ERROR] %s' % _("An internal error has occurred. See shell.\n")
  8127. msg += traceback.format_exc()
  8128. app_obj.inform.emit(msg)
  8129. return "fail"
  8130. if gerber_obj.is_empty():
  8131. app_obj.inform.emit('[ERROR_NOTCL] %s' %
  8132. _("Object is not Gerber file or empty. Aborting object creation."))
  8133. return "fail"
  8134. self.app.log.debug("open_gerber()")
  8135. with self.app.proc_container.new(_("Opening Gerber")):
  8136. # Object name
  8137. name = outname or filename.split('/')[-1].split('\\')[-1]
  8138. # # ## Object creation # ##
  8139. ret_val = self.app.app_obj.new_object("gerber", name, obj_init, autoselected=False, plot=plot)
  8140. if ret_val == 'fail':
  8141. if from_tcl:
  8142. filename = self.defaults['global_tcl_path'] + '/' + name
  8143. ret_val = self.app.app_obj.new_object("gerber", name, obj_init, autoselected=False, plot=plot)
  8144. if ret_val == 'fail':
  8145. self.inform.emit('[ERROR_NOTCL]%s' % _('Open Gerber failed. Probable not a Gerber file.'))
  8146. return 'fail'
  8147. # Register recent file
  8148. self.app.file_opened.emit("gerber", filename)
  8149. # appGUI feedback
  8150. self.app.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  8151. def open_excellon(self, filename, outname=None, plot=True, from_tcl=False):
  8152. """
  8153. Opens an Excellon file, parses it and creates a new object for
  8154. it in the program. Thread-safe.
  8155. :param outname: Name of the resulting object. None causes the name to be that of the file.
  8156. :param filename: Excellon file filename
  8157. :type filename: str
  8158. :param plot: boolean, to plot or not the resulting object
  8159. :param from_tcl: True if run from Tcl Shell
  8160. :return: None
  8161. """
  8162. self.app.log.debug("open_excellon()")
  8163. # How the object should be initialized
  8164. def obj_init(excellon_obj, app_obj):
  8165. try:
  8166. ret = excellon_obj.parse_file(filename=filename)
  8167. if ret == "fail":
  8168. app_obj.log.debug("Excellon parsing failed.")
  8169. self.inform.emit('[ERROR_NOTCL] %s' % _("This is not Excellon file."))
  8170. return "fail"
  8171. except IOError:
  8172. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Cannot open file"), filename))
  8173. app_obj.log.debug("Could not open Excellon object.")
  8174. return "fail"
  8175. except Exception:
  8176. msg = '[ERROR_NOTCL] %s' % _("An internal error has occurred. See shell.\n")
  8177. msg += traceback.format_exc()
  8178. app_obj.inform.emit(msg)
  8179. return "fail"
  8180. ret = excellon_obj.create_geometry()
  8181. if ret == 'fail':
  8182. app_obj.log.debug("Could not create geometry for Excellon object.")
  8183. return "fail"
  8184. for tool in excellon_obj.tools:
  8185. if excellon_obj.tools[tool]['solid_geometry']:
  8186. return
  8187. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("No geometry found in file"), filename))
  8188. return "fail"
  8189. with self.app.proc_container.new(_("Opening Excellon.")):
  8190. # Object name
  8191. name = outname or filename.split('/')[-1].split('\\')[-1]
  8192. ret_val = self.app.app_obj.new_object("excellon", name, obj_init, autoselected=False, plot=plot)
  8193. if ret_val == 'fail':
  8194. if from_tcl:
  8195. filename = self.defaults['global_tcl_path'] + '/' + name
  8196. ret_val = self.app.app_obj.new_object("excellon", name, obj_init, autoselected=False, plot=plot)
  8197. if ret_val == 'fail':
  8198. self.inform.emit('[ERROR_NOTCL] %s' %
  8199. _('Open Excellon file failed. Probable not an Excellon file.'))
  8200. return
  8201. # Register recent file
  8202. self.app.file_opened.emit("excellon", filename)
  8203. # appGUI feedback
  8204. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  8205. def open_gcode(self, filename, outname=None, force_parsing=None, plot=True, from_tcl=False):
  8206. """
  8207. Opens a G-gcode file, parses it and creates a new object for
  8208. it in the program. Thread-safe.
  8209. :param filename: G-code file filename
  8210. :param outname: Name of the resulting object. None causes the name to be that of the file.
  8211. :param force_parsing:
  8212. :param plot: If True plot the object on canvas
  8213. :param from_tcl: True if run from Tcl Shell
  8214. :return: None
  8215. """
  8216. self.app.log.debug("open_gcode()")
  8217. # How the object should be initialized
  8218. def obj_init(job_obj, app_obj_):
  8219. """
  8220. :param job_obj: the resulting object
  8221. :type app_obj_: App
  8222. """
  8223. assert isinstance(app_obj_, App), \
  8224. "Initializer expected App, got %s" % type(app_obj_)
  8225. app_obj_.inform.emit('%s...' % _("Reading GCode file"))
  8226. try:
  8227. f = open(filename)
  8228. gcode = f.read()
  8229. f.close()
  8230. except IOError:
  8231. app_obj_.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open"), filename))
  8232. return "fail"
  8233. job_obj.gcode = gcode
  8234. gcode_ret = job_obj.gcode_parse(force_parsing=force_parsing)
  8235. if gcode_ret == "fail":
  8236. self.inform.emit('[ERROR_NOTCL] %s' % _("This is not GCODE"))
  8237. return "fail"
  8238. job_obj.create_geometry()
  8239. with self.app.proc_container.new(_("Opening G-Code.")):
  8240. # Object name
  8241. name = outname or filename.split('/')[-1].split('\\')[-1]
  8242. # New object creation and file processing
  8243. ret_val = self.app.app_obj.new_object("cncjob", name, obj_init, autoselected=False, plot=plot)
  8244. if ret_val == 'fail':
  8245. if from_tcl:
  8246. filename = self.defaults['global_tcl_path'] + '/' + name
  8247. ret_val = self.app.app_obj.new_object("cncjob", name, obj_init, autoselected=False, plot=plot)
  8248. if ret_val == 'fail':
  8249. self.inform.emit('[ERROR_NOTCL] %s' %
  8250. _("Failed to create CNCJob Object. Probable not a GCode file. "
  8251. "Try to load it from File menu.\n "
  8252. "Attempting to create a FlatCAM CNCJob Object from "
  8253. "G-Code file failed during processing"))
  8254. return "fail"
  8255. # Register recent file
  8256. self.app.file_opened.emit("cncjob", filename)
  8257. # appGUI feedback
  8258. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  8259. def open_hpgl2(self, filename, outname=None):
  8260. """
  8261. Opens a HPGL2 file, parses it and creates a new object for
  8262. it in the program. Thread-safe.
  8263. :param outname: Name of the resulting object. None causes the name to be that of the file.
  8264. :param filename: HPGL2 file filename
  8265. :return: None
  8266. """
  8267. filename = filename
  8268. # How the object should be initialized
  8269. def obj_init(geo_obj, app_obj):
  8270. assert isinstance(geo_obj, GeometryObject), \
  8271. "Expected to initialize a GeometryObject but got %s" % type(geo_obj)
  8272. # Opening the file happens here
  8273. obj = HPGL2(self)
  8274. try:
  8275. HPGL2.parse_file(obj, filename)
  8276. except IOError:
  8277. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open file"), filename))
  8278. return "fail"
  8279. except ParseError as err:
  8280. app_obj.inform.emit('[ERROR_NOTCL] %s: %s. %s' % (_("Failed to parse file"), filename, str(err)))
  8281. app_obj.log.error(str(err))
  8282. return "fail"
  8283. except Exception as e:
  8284. app_obj.log.debug("App.open_hpgl2() --> %s" % str(e))
  8285. msg = '[ERROR] %s' % _("An internal error has occurred. See shell.\n")
  8286. msg += traceback.format_exc()
  8287. app_obj.inform.emit(msg)
  8288. return "fail"
  8289. geo_obj.multigeo = True
  8290. geo_obj.solid_geometry = deepcopy(obj.solid_geometry)
  8291. geo_obj.tools = deepcopy(obj.tools)
  8292. geo_obj.source_file = deepcopy(obj.source_file)
  8293. del obj
  8294. if not geo_obj.solid_geometry:
  8295. app_obj.inform.emit('[ERROR_NOTCL] %s' %
  8296. _("Object is not HPGL2 file or empty. Aborting object creation."))
  8297. return "fail"
  8298. self.app.log.debug("open_hpgl2()")
  8299. with self.app.proc_container.new(_("Opening HPGL2")):
  8300. # Object name
  8301. name = outname or filename.split('/')[-1].split('\\')[-1]
  8302. # # ## Object creation # ##
  8303. ret = self.app.app_obj.new_object("geometry", name, obj_init, autoselected=False)
  8304. if ret == 'fail':
  8305. self.inform.emit('[ERROR_NOTCL]%s' % _(' Open HPGL2 failed. Probable not a HPGL2 file.'))
  8306. return 'fail'
  8307. # Register recent file
  8308. self.app.file_opened.emit("geometry", filename)
  8309. # appGUI feedback
  8310. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  8311. def open_script(self, filename, outname=None, silent=False):
  8312. """
  8313. Opens a Script file, parses it and creates a new object for
  8314. it in the program. Thread-safe.
  8315. :param outname: Name of the resulting object. None causes the name to be that of the file.
  8316. :param filename: Script file filename
  8317. :param silent: If True there will be no messages printed to StatusBar
  8318. :return: None
  8319. """
  8320. def obj_init(script_obj, app_obj):
  8321. assert isinstance(script_obj, ScriptObject), \
  8322. "Expected to initialize a ScriptObject but got %s" % type(script_obj)
  8323. if silent is False:
  8324. app_obj.inform.emit('[success] %s' % _("TCL script file opened in Code Editor."))
  8325. try:
  8326. script_obj.parse_file(filename)
  8327. except IOError:
  8328. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open file"), filename))
  8329. return "fail"
  8330. except ParseError as err:
  8331. app_obj.inform.emit('[ERROR_NOTCL] %s: %s. %s' % (_("Failed to parse file"), filename, str(err)))
  8332. app_obj.log.error(str(err))
  8333. return "fail"
  8334. except Exception as e:
  8335. app_obj.log.debug("App.open_script() -> %s" % str(e))
  8336. msg = '[ERROR] %s' % _("An internal error has occurred. See shell.\n")
  8337. msg += traceback.format_exc()
  8338. app_obj.inform.emit(msg)
  8339. return "fail"
  8340. self.app.log.debug("open_script()")
  8341. with self.app.proc_container.new(_("Opening TCL Script...")):
  8342. # Object name
  8343. script_name = outname or filename.split('/')[-1].split('\\')[-1]
  8344. # Object creation
  8345. ret_val = self.app.app_obj.new_object("script", script_name, obj_init, autoselected=False, plot=False)
  8346. if ret_val == 'fail':
  8347. filename = self.defaults['global_tcl_path'] + '/' + script_name
  8348. ret_val = self.app.app_obj.new_object("script", script_name, obj_init, autoselected=False, plot=False)
  8349. if ret_val == 'fail':
  8350. self.inform.emit('[ERROR_NOTCL]%s' % _('Failed to open TCL Script.'))
  8351. return 'fail'
  8352. # Register recent file
  8353. self.app.file_opened.emit("script", filename)
  8354. # appGUI feedback
  8355. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  8356. def open_config_file(self, filename, run_from_arg=None):
  8357. """
  8358. Loads a config file from the specified file.
  8359. :param filename: Name of the file from which to load.
  8360. :param run_from_arg: if True the FlatConfig file will be open as an command line argument
  8361. :return: None
  8362. """
  8363. self.app.log.debug("Opening config file: " + filename)
  8364. if run_from_arg:
  8365. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  8366. "Canvas initialization finished in"),
  8367. '%.2f' % self.app.used_time,
  8368. _("Opening FlatCAM Config file.")),
  8369. alignment=Qt.AlignBottom | Qt.AlignLeft,
  8370. color=QtGui.QColor("gray"))
  8371. # # add the tab if it was closed
  8372. # self.ui.plot_tab_area.addTab(self.ui.text_editor_tab, _("Code Editor"))
  8373. # # first clear previous text in text editor (if any)
  8374. # self.ui.text_editor_tab.code_editor.clear()
  8375. #
  8376. # # Switch plot_area to CNCJob tab
  8377. # self.ui.plot_tab_area.setCurrentWidget(self.ui.text_editor_tab)
  8378. # close the Code editor if already open
  8379. if self.app.toggle_codeeditor:
  8380. self.app.on_toggle_code_editor()
  8381. self.app.on_toggle_code_editor()
  8382. try:
  8383. if filename:
  8384. f = QtCore.QFile(filename)
  8385. if f.open(QtCore.QIODevice.ReadOnly):
  8386. stream = QtCore.QTextStream(f)
  8387. code_edited = stream.readAll()
  8388. self.app.text_editor_tab.load_text(code_edited, clear_text=True, move_to_start=True)
  8389. f.close()
  8390. except IOError:
  8391. self.app.log.error("Failed to open config file: %s" % filename)
  8392. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open config file"), filename))
  8393. return
  8394. def open_project(self, filename, run_from_arg=None, plot=True, cli=None, from_tcl=False):
  8395. """
  8396. Loads a project from the specified file.
  8397. 1) Loads and parses file
  8398. 2) Registers the file as recently opened.
  8399. 3) Calls on_file_new()
  8400. 4) Updates options
  8401. 5) Calls app_obj.new_object() with the object's from_dict() as init method.
  8402. 6) Calls plot_all() if plot=True
  8403. :param filename: Name of the file from which to load.
  8404. :param run_from_arg: True if run for arguments
  8405. :param plot: If True plot all objects in the project
  8406. :param cli: Run from command line
  8407. :param from_tcl: True if run from Tcl Sehll
  8408. :return: None
  8409. """
  8410. self.app.log.debug("Opening project: " + filename)
  8411. # block autosaving while a project is loaded
  8412. self.app.block_autosave = True
  8413. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  8414. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  8415. if cli is None:
  8416. self.app.set_ui_title(name=_("Loading Project ... Please Wait ..."))
  8417. if run_from_arg:
  8418. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  8419. "Canvas initialization finished in"),
  8420. '%.2f' % self.app.used_time,
  8421. _("Opening FlatCAM Project file.")),
  8422. alignment=Qt.AlignBottom | Qt.AlignLeft,
  8423. color=QtGui.QColor("gray"))
  8424. # Open and parse an uncompressed Project file
  8425. try:
  8426. f = open(filename, 'r')
  8427. except IOError:
  8428. if from_tcl:
  8429. name = filename.split('/')[-1].split('\\')[-1]
  8430. filename = self.defaults['global_tcl_path'] + '/' + name
  8431. try:
  8432. f = open(filename, 'r')
  8433. except IOError:
  8434. self.app.log.error("Failed to open project file: %s" % filename)
  8435. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open project file"), filename))
  8436. return
  8437. else:
  8438. self.app.log.error("Failed to open project file: %s" % filename)
  8439. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open project file"), filename))
  8440. return
  8441. try:
  8442. d = json.load(f, object_hook=dict2obj)
  8443. except Exception as e:
  8444. self.app.log.error(
  8445. "Failed to parse project file, trying to see if it loads as an LZMA archive: %s because %s" %
  8446. (filename, str(e)))
  8447. f.close()
  8448. # Open and parse a compressed Project file
  8449. try:
  8450. with lzma.open(filename) as f:
  8451. file_content = f.read().decode('utf-8')
  8452. d = json.loads(file_content, object_hook=dict2obj)
  8453. except Exception as e:
  8454. self.app.log.error("Failed to open project file: %s with error: %s" % (filename, str(e)))
  8455. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open project file"), filename))
  8456. return
  8457. # Clear the current project
  8458. # # NOT THREAD SAFE # ##
  8459. if run_from_arg is True:
  8460. pass
  8461. elif cli is True:
  8462. self.app.delete_selection_shape()
  8463. else:
  8464. self.on_file_new()
  8465. # Project options
  8466. self.app.options.update(d['options'])
  8467. self.app.project_filename = filename
  8468. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  8469. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  8470. if cli is None:
  8471. self.app.set_screen_units(self.app.options["units"])
  8472. # Re create objects
  8473. self.app.log.debug(" **************** Started PROEJCT loading... **************** ")
  8474. for obj in d['objs']:
  8475. def obj_init(obj_inst, app_inst):
  8476. try:
  8477. obj_inst.from_dict(obj)
  8478. except Exception as e:
  8479. self.app.log('App.open_project() --> ' + str(e))
  8480. return 'fail'
  8481. self.app.log.debug("Recreating from opened project an %s object: %s" %
  8482. (obj['kind'].capitalize(), obj['options']['name']))
  8483. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  8484. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  8485. if cli is None:
  8486. self.app.set_ui_title(name="{} {}: {}".format(
  8487. _("Loading Project ... restoring"), obj['kind'].upper(), obj['options']['name']))
  8488. self.app.app_obj.new_object(obj['kind'], obj['options']['name'], obj_init, plot=plot)
  8489. self.inform.emit('[success] %s: %s' % (_("Project loaded from"), filename))
  8490. self.app.should_we_save = False
  8491. self.app.file_opened.emit("project", filename)
  8492. # restore autosaving after a project was loaded
  8493. self.app.block_autosave = False
  8494. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  8495. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  8496. if cli is None:
  8497. self.app.set_ui_title(name=self.app.project_filename)
  8498. self.app.log.debug(" **************** Finished PROJECT loading... **************** ")
  8499. def save_project(self, filename, quit_action=False, silent=False, from_tcl=False):
  8500. """
  8501. Saves the current project to the specified file.
  8502. :param filename: Name of the file in which to save.
  8503. :type filename: str
  8504. :param quit_action: if the project saving will be followed by an app quit; boolean
  8505. :param silent: if True will not display status messages
  8506. :param from_tcl True is run from Tcl Shell
  8507. :return: None
  8508. """
  8509. self.app.log.debug("save_project()")
  8510. self.app.save_in_progress = True
  8511. with self.app.proc_container.new(_("Saving FlatCAM Project")):
  8512. # Capture the latest changes
  8513. # Current object
  8514. try:
  8515. current_object = self.app.collection.get_active()
  8516. if current_object:
  8517. current_object.read_form()
  8518. except Exception as e:
  8519. self.app.log.debug("save_project() --> There was no active object. Skipping read_form. %s" % str(e))
  8520. # Serialize the whole project
  8521. d = {
  8522. "objs": [obj.to_dict() for obj in self.app.collection.get_list()],
  8523. "options": self.options,
  8524. "version": self.version
  8525. }
  8526. if self.defaults["global_save_compressed"] is True:
  8527. with lzma.open(filename, "w", preset=int(self.defaults['global_compression_level'])) as f:
  8528. g = json.dumps(d, default=to_dict, indent=2, sort_keys=True).encode('utf-8')
  8529. # # Write
  8530. f.write(g)
  8531. self.inform.emit('[success] %s: %s' % (_("Project saved to"), filename))
  8532. else:
  8533. # Open file
  8534. try:
  8535. f = open(filename, 'w')
  8536. except IOError:
  8537. self.app.log.error("Failed to open file for saving: %s", filename)
  8538. self.inform.emit('[ERROR_NOTCL] %s' % _("The object is used by another application."))
  8539. return
  8540. # Write
  8541. json.dump(d, f, default=to_dict, indent=2, sort_keys=True)
  8542. f.close()
  8543. # verification of the saved project
  8544. # Open and parse
  8545. try:
  8546. saved_f = open(filename, 'r')
  8547. except IOError:
  8548. if silent is False:
  8549. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  8550. (_("Failed to verify project file"), filename, _("Retry to save it.")))
  8551. return
  8552. try:
  8553. saved_d = json.load(saved_f, object_hook=dict2obj)
  8554. except Exception:
  8555. if silent is False:
  8556. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  8557. (_("Failed to parse saved project file"), filename, _("Retry to save it.")))
  8558. f.close()
  8559. return
  8560. saved_f.close()
  8561. if silent is False:
  8562. if 'version' in saved_d:
  8563. self.inform.emit('[success] %s: %s' % (_("Project saved to"), filename))
  8564. else:
  8565. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  8566. (_("Failed to parse saved project file"), filename, _("Retry to save it.")))
  8567. tb_settings = QSettings("Open Source", "FlatCAM")
  8568. lock_state = self.app.ui.lock_action.isChecked()
  8569. tb_settings.setValue('toolbar_lock', lock_state)
  8570. # This will write the setting to the platform specific storage.
  8571. del tb_settings
  8572. # if quit:
  8573. # t = threading.Thread(target=lambda: self.check_project_file_size(1, filename=filename))
  8574. # t.start()
  8575. self.app.start_delayed_quit(delay=500, filename=filename, should_quit=quit_action)
  8576. def save_source_file(self, obj_name, filename, use_thread=True):
  8577. """
  8578. Exports a FlatCAM Object to an Gerber/Excellon file.
  8579. :param obj_name: the name of the FlatCAM object for which to save it's embedded source file
  8580. :param filename: Path to the Gerber file to save to.
  8581. :param use_thread: if to be run in a separate thread
  8582. :return:
  8583. """
  8584. if filename is None:
  8585. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  8586. is not None else self.defaults["global_last_folder"]
  8587. self.app.log.debug("save source file()")
  8588. obj = self.app.collection.get_by_name(obj_name)
  8589. file_string = StringIO(obj.source_file)
  8590. time_string = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  8591. if file_string.getvalue() == '':
  8592. self.inform.emit('[ERROR_NOTCL] %s' %
  8593. _("Save cancelled because source file is empty. Try to export the file."))
  8594. return 'fail'
  8595. try:
  8596. with open(filename, 'w') as file:
  8597. file.writelines('G04*\n')
  8598. file.writelines('G04 %s (RE)GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s*\n' %
  8599. (obj.kind.upper(), str(self.app.version), str(self.app.version_date)))
  8600. file.writelines('G04 Filename: %s*\n' % str(obj_name))
  8601. file.writelines('G04 Created on : %s*\n' % time_string)
  8602. for line in file_string:
  8603. file.writelines(line)
  8604. except PermissionError:
  8605. self.inform.emit('[WARNING] %s' %
  8606. _("Permission denied, saving not possible.\n"
  8607. "Most likely another app is holding the file open and not accessible."))
  8608. return 'fail'
  8609. def on_file_savedefaults(self):
  8610. """
  8611. Callback for menu item File->Save Defaults. Saves application default options
  8612. ``self.defaults`` to current_defaults.FlatConfig.
  8613. :return: None
  8614. """
  8615. self.app.preferencesUiManager.save_defaults()
  8616. # end of file